Java 最近的 LocalDate
Java Closest LocalDate
我有一个 LocalDate 对象列表 (dates
),我想在列表中找到最接近给定日期 (milestoneDate
) 的条目。
最接近意味着日期可以在 milestoneDate
之前或之后,但差异最小。例如,milestoneDate
前一天的内容比 milestoneDate
.
后 2 天的内容更接近
到目前为止,我的最佳想法是将 dates
中的值转换为 EpochSecond,然后获取该值与 milestoneDate
的 toEpochSecond
之间的差值的绝对值,并且select 最小值。
long milestoneSeconds = milestoneDate.atStartOfDay().toEpochSecond(ZoneOffset.UTC);
return dates.stream().sorted((x, y) -> {
long xDiff = Math.abs(x.atStartOfDay().toEpochSecond(ZoneOffset.UTC) - milestoneSeconds);
long yDiff = Math.abs(y.atStartOfDay().toEpochSecond(ZoneOffset.UTC) - milestoneSeconds);
return (int) (xDiff - yDiff);
}).findFirst();
虽然我怀疑这会起作用,但感觉有点沉重。有没有更优雅的方法来做到这一点?
您可以直接在列表中找到里程碑日期与每个日期之间的天数。无需转换为纪元秒
dates.stream().min(Comparator.comparingLong(
x -> Math.abs(ChronoUnit.DAYS.between(x, milestoneDate))
));
请注意,在某些情况下,可能有 2 个日期与里程碑日期同样接近 - 一个在它之前,一个在它之后。如果你在这种情况下更喜欢选择哪一个,你可以在比较器中添加一个thenComparing
:
// gets the date before
dates.stream().min(Comparator.<LocalDate>comparingLong(
x -> Math.abs(ChronoUnit.DAYS.between(x, milestoneDate))
).thenComparing(Comparator.naturalOrder()));
// gets the date after
dates.stream().min(Comparator.<LocalDate>comparingLong(
x -> Math.abs(ChronoUnit.DAYS.between(x, milestoneDate))
).thenComparing(
Comparator.<LocalDate>naturalOrder().reversed()
));
有点遗憾Java无法推断类型参数:(
我有一个 LocalDate 对象列表 (dates
),我想在列表中找到最接近给定日期 (milestoneDate
) 的条目。
最接近意味着日期可以在 milestoneDate
之前或之后,但差异最小。例如,milestoneDate
前一天的内容比 milestoneDate
.
到目前为止,我的最佳想法是将 dates
中的值转换为 EpochSecond,然后获取该值与 milestoneDate
的 toEpochSecond
之间的差值的绝对值,并且select 最小值。
long milestoneSeconds = milestoneDate.atStartOfDay().toEpochSecond(ZoneOffset.UTC);
return dates.stream().sorted((x, y) -> {
long xDiff = Math.abs(x.atStartOfDay().toEpochSecond(ZoneOffset.UTC) - milestoneSeconds);
long yDiff = Math.abs(y.atStartOfDay().toEpochSecond(ZoneOffset.UTC) - milestoneSeconds);
return (int) (xDiff - yDiff);
}).findFirst();
虽然我怀疑这会起作用,但感觉有点沉重。有没有更优雅的方法来做到这一点?
您可以直接在列表中找到里程碑日期与每个日期之间的天数。无需转换为纪元秒
dates.stream().min(Comparator.comparingLong(
x -> Math.abs(ChronoUnit.DAYS.between(x, milestoneDate))
));
请注意,在某些情况下,可能有 2 个日期与里程碑日期同样接近 - 一个在它之前,一个在它之后。如果你在这种情况下更喜欢选择哪一个,你可以在比较器中添加一个thenComparing
:
// gets the date before
dates.stream().min(Comparator.<LocalDate>comparingLong(
x -> Math.abs(ChronoUnit.DAYS.between(x, milestoneDate))
).thenComparing(Comparator.naturalOrder()));
// gets the date after
dates.stream().min(Comparator.<LocalDate>comparingLong(
x -> Math.abs(ChronoUnit.DAYS.between(x, milestoneDate))
).thenComparing(
Comparator.<LocalDate>naturalOrder().reversed()
));
有点遗憾Java无法推断类型参数:(