我在Temp类中有两个日期字段,分别是validFromDate和asOfDate。我有清单。我需要将标志whihc是其validFromDate最接近asOfDate的记录的类属性之一设置为true

例如

List<temp> {
    Temp1:
        asOfDate: 2018-01-04
        validFrom: 2018-01-01
    Temp2:
        asOfDate: 2018-01-04
        validFrom: 2018-01-02
    Temp3:
        asOfDate: 2018-01-04
        validFrom: 2018-01-03
}


o / p应该为Temp3,因为此validFrom最接近asOfdate。我将为此Temp2将标志设置为true

如何使用Java 8流实现此目标?

最佳答案

  temp.stream()
      .map(x -> new SimpleEntry<>(x, ChronoUnit.DAYS.between(x.getAsOfDate(), x.getValidFrom())))
      .min(Comparator.comparingLong(Entry::getValue))
      .map(Entry::getKey)
      .orElse(...);


或更简单:

test.stream()
    .min(Comparator.comparingLong(x -> ChronoUnit.DAYS.between(x.asOfDate , x.validFrom)));

10-06 07:09