如何使用API​​ Stream与ZonedDateTime一起使用?

问题描述

我正在尝试将此使用经典FOR的方法传递给Stream API

public static List<DateBucket> bucketize(zoneddatetime fromDate,zoneddatetime toDate,int bucketSize,ChronoUnit bucketSizeUnit) {
      

    List<DateBucket> buckets = new ArrayList<>();
       boolean reachedDate = false;
       for (int i = 0; !reachedDate; i++) {
           zoneddatetime minDate = fromDate.plus(i * bucketSize,bucketSizeUnit);
           zoneddatetime maxDate = fromDate.plus((i + 1) * bucketSize,bucketSizeUnit);
           reachedDate = toDate.isBefore(maxDate);
           buckets.add(new DateBucket(minDate.toInstant(),maxDate.toInstant()));
       }

   return buckets;
}

类似这样的东西:

List<DateBucket> buckets = 
    buckets.stream().map(i-> new DateBucket(minDate.toInstant(),maxDate.toInstant()))
                    .collect(Collectors.toList());

谢谢

解决方法

public static List<DateBucket> bucketize(ZonedDateTime fromDate,ZonedDateTime toDate,int bucketSize,ChronoUnit bucketSizeUnit) {
    return Stream.iterate(fromDate,zdt -> zdt.isBefore(toDate),zdt -> zdt.plus(bucketSize,bucketSizeUnit))
            .map(zdt -> new DateBucket(zdt.toInstant(),zdt.plus(bucketSize,bucketSizeUnit).toInstant()))
            .collect(Collectors.toList());
}

要尝试:

    ZoneId zone = ZoneId.of("Asia/Urumqi");
    ZonedDateTime from = ZonedDateTime.of(2020,8,18,9,zone);
    ZonedDateTime to = ZonedDateTime.of(2020,20,17,zone);
    
    List<DateBucket> buckets = bucketize(from,to,1,ChronoUnit.DAYS);
    buckets.forEach(System.out::println);

输出:

2020-08-18T03:00:00Z - 2020-08-19T03:00:00Z
2020-08-19T03:00:00Z - 2020-08-20T03:00:00Z
2020-08-20T03:00:00Z - 2020-08-21T03:00:00Z

我不确定在此处使用流操作是否有利,但是如您所见,当然有可能。

我使用的iterate方法是Java 9中引入的。