[英]How to get minimum LocalDateTime from array in Java
I have an array:我有一个数组:
LocalDateTime[] onTimes
I would like to find an efficient way (without iteration) of finding the minimum LocalDateTime.我想找到一种找到最小 LocalDateTime 的有效方法(无需迭代)。
Is there a quick way to do this?有没有快速的方法来做到这一点?
You could, conceivably, use recursion;可以想象,你可以使用递归; but I would not recommend that for performance.
但我不建议这样做以提高性能。 The best way I can think of is using the streams api like
我能想到的最好的方法是使用流 api 之类的
LocalDateTime min = Arrays.stream(onTimes).min(Comparator.naturalOrder())
.orElseThrow();
Note: This still iterates all elements internally to find the minimum.注意:这仍然在内部迭代所有元素以找到最小值。
For completeness sake;为了完整起见; to do this without iteration, as I said, might be done recursively.
如我所说,在没有迭代的情况下执行此操作可能会递归完成。
public static LocalDateTime getMinimum(LocalDateTime[] onTimes) {
return getMinimum(onTimes, 0);
}
private static LocalDateTime getMinimum(LocalDateTime[] onTimes, int i) {
if (i + 1 < onTimes.length) {
return min(onTimes[i], getMinimum(onTimes, i + 1));
} else {
return onTimes[i];
}
}
private static LocalDateTime min(LocalDateTime a, LocalDateTime b) {
if (a.compareTo(b) <= 0) {
return a;
}
return b;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.