使用 Java 8 次 API 根据当前日期用三个月的最后几天(周一至周日)填充 arrayList

Populate an arrayList with last days of week(Monday-Sunday) for three months based on current date using Java 8 time API

开发一个时间表选择页面,该页面应预先填充过去三个月的周末日期列表。需要 O(n) 使用 Java 8 次 API.

的过程

我当前的解决方案检查当前日期是否为星期日,如果不是,则找出本周末,然后迭代三个月。寻找优化的解决方案。

Java 8 个答案如下(如果您只查找星期日):

LocalDate closestSunday = LocalDate.now().with(TemporalAdjusters.previousOrSame(DayOfWeek.SUNDAY));
LocalDate firstSunday = closestSunday.minusMonths(3);

List<LocalDate> sundays = new ArrayList<>();

for (; !closestSunday.isBefore(firstSunday); closestSunday = closestSunday.minusWeeks(1)) {
    sundays.add(closestSunday);
}

我会使用 Stream 方法,但我宁愿等 8 天直到 JDK 9 发布,这样我就可以使用 Stream#takeWhile.

编辑:如果您真的想要一个利用 JDK 8 的 Stream 方法,那么以下代码在逻辑上等同于上面的代码:

LocalDate closestSunday = LocalDate.now().with(TemporalAdjusters.previousOrSame(DayOfWeek.SUNDAY));
LocalDate secondSunday = closestSunday.minusMonths(3).plusWeeks(1);

List<LocalDate> sundays = new ArrayList<>();

Stream.iterate(closestSunday, date -> date.minusWeeks(1))
      .peek(sundays::add)
      .allMatch(date -> date.isAfter(secondSunday));

我回答过类似的问题

我们要检查上周六和三个月前的日期之间相隔了多少周。然后是简单的数学:

LocalDate lastSunday = LocalDate.now()
  .with(TemporalAdjusters.previousOrSame(DayOfWeek.SUNDAY));

long weeks = ChronoUnit.WEEKS.between(lastSunday.minusMonths(3L), lastSunday);

List<LocalDate> collect = Stream.iterate(lastSunday.minusWeeks(weeks), d -> d.plusWeeks(1L))
  .limit(weeks + 1)
  .collect(Collectors.toList());

在JDK9中有一个新方法,datesUntil

// today, but make sure you consider time-zones when using this method
LocalDate today = LocalDate.now();

// find the next Sunday
LocalDate endSun = today.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));

// find 3 months earlier (there are 13 weeks in 3 months)
LocalDate startSun = endSun.minusWeeks(13);

// find dates
Stream<LocalDate> dates = startSun.datesUntil(endSun, Period.ofWeeks(1));