Bas*_*que 3 java collections for-loop java-stream
我们如何使用Java Streams方法收集for
循环中生成的对象?
例如,这里我们LocalDate
为一个月中的每一天生成一个对象,YearMonth
通过重复调用来表示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 );
}
Run Code Online (Sandbox Code Playgroud)
可以使用流重写吗?
它可以从IntStream开始重写:
YearMonth ym = YearMonth.of(2017, Month.AUGUST);
List<LocalDate> dates =
IntStream.rangeClosed(1, ym.lengthOfMonth())
.mapToObj(ym::atDay)
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
IntStream中的每个整数值都映射到所需的日期,然后在列表中收集日期.