【问题标题】:How to work with ZonedDateTime using API Stream?如何使用 API Stream 使用 ZonedDateTime?
【发布时间】:2020-08-15 22:15:00
【问题描述】:

我正在尝试将这个使用经典 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());

谢谢

【问题讨论】:

  • 您使用的是什么版本的 Java?如果可能的话,这在 8 中将比在 9 中更难。此外,bucketSizebucketSizeUnit 一起可能更好地表示为PeriodDurationZonedDateTime 很糟糕,因为不清楚是哪一个)
  • @LouisWasserman 该方法可能只接受TemporalAmount。这是DurationPeriod 都实现的接口。
  • @OleV.V.虽然这是真的,但将DurationPeriod 混为一谈也是有问题的。

标签: java java-stream zoneddatetime


【解决方案1】:
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, 0, 0, 0, zone);
    ZonedDateTime to = ZonedDateTime.of(2020, 8, 20, 17, 0, 0, 0, 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 中引入的。

【讨论】:

  • 对不起@Ole V.V,我将创建另一个带有问题的帖子。感谢您对此的良好回答
  • 没关系。学会正确使用本网站需要一点时间。
猜你喜欢
  • 2017-08-13
  • 1970-01-01
  • 2014-07-26
  • 2021-01-29
  • 1970-01-01
  • 2021-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多