I have an array:
LocalDateTime[] onTimes
I would like to find an efficient way (without iteration) of finding the minimum LocalDateTime.
Is there a quick way to do this?
CodePudding user response:
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
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;
}