使用Java流来收集`for`循环中生成的对象
发布时间:2020-12-15 04:48:45 所属栏目:Java 来源:网络整理
导读:我们如何使用 Java Streams方法收集for循环中生成的对象? 例如,这里我们通过重复调用 YearMonth::atDay 为 YearMonth 所代表的一个月中的每一天生成一个 LocalDate 对象. YearMonth ym = YearMonth.of( 2017,Month.AUGUST ) ;ListLocalDate dates = new Arr
我们如何使用
Java Streams方法收集for循环中生成的对象?
例如,这里我们通过重复调用 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 ); } 可以使用流重写吗? 解决方法
它可以从IntStream开始重写:
YearMonth ym = YearMonth.of(2017,Month.AUGUST); List<LocalDate> dates = IntStream.rangeClosed(1,ym.lengthOfMonth()) .mapToObj(ym::atDay) .collect(Collectors.toList()); IntStream中的每个整数值都映射到所需的日期,然后在列表中收集日期. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |