使用Java流来收集在for循环中生成的对象 [英] Use Java streams to collect objects generated in a `for` loop

查看:144
本文介绍了使用Java流来收集在for循环中生成的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们如何使用Java Streams方法来收集在中为循环生成的对象?

例如

,这里我们生成一个 LocalDate 对象rel =nofollow noreferrer> YearMonth 通过反复调用 YearMonth :: atDay

  YearMonth ym = YearMonth.of(2017,Month.AUGUST); 
列表< LocalDate> dates = new ArrayList<>(ym.lengthOfMonth());
for(int i = 1; i< = ym.lengthOfMonth(); i ++){
LocalDate localDate = ym.atDay(i);
dates.add(localDate);



$ b $ p
$ b

可以用流重写吗?
<可以用IntStream开始重写:

  YearMonth ym = YearMonth.of(2017,Month.AUGUST); 
列表< LocalDate>日期=
IntStream.rangeClosed(1,ym.lengthOfMonth())
.mapToObj(ym :: atDay)
.collect(Collectors.toList());

将IntStream中的每个整数值映射到所需日期,然后将日期收集到列表中。


How can we use the Java Streams approach to collecting objects generated in a for loop?

For example, here we generate one LocalDate object for each day in a month represented by YearMonth by repeatedly calling YearMonth::atDay.

YearMonth ym = YearMonth.of( 2017 , Month.AUGUST ) ;
List<LocalDate> dates = new ArrayList<>( ym.lengthOfMonth() );
for ( int i = 1 ; i <= ym.lengthOfMonth () ; i ++ ) {
    LocalDate localDate = ym.atDay ( i );
    dates.add( localDate );
}

Can this be rewritten using streams?

解决方案

It can be rewritten starting with an IntStream:

YearMonth ym = YearMonth.of(2017, Month.AUGUST);
List<LocalDate> dates =
        IntStream.rangeClosed(1, ym.lengthOfMonth())
        .mapToObj(ym::atDay)
        .collect(Collectors.toList());

Each integer value from the IntStream is mapped to the desired date and then the dates are collected in a list.

这篇关于使用Java流来收集在for循环中生成的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆