Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is there a quick way to do this?

>Solution :

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading