javadatemindate-comparison

Find the earliest date among 3 dates


I have three dates in Java: a, b, c. Any or all of these dates may be null. What's the most efficient way of determining the earliest date among a,b,c, without having a massive if-else block? I would want a the actual date that is earliest among a,b,c. Any date is better than a null date.


Solution

  • There's no getting around null checking, but with some refactoring you can make it painless.

    Create a method that safely compares two dates:

    /**
     * Safely compare two dates, null being considered "greater" than a Date
     * @return the earliest of the two
     */
    public static Date least(Date a, Date b) {
        return a == null ? b : (b == null ? a : (a.before(b) ? a : b));
    }
    

    then combine calls to that:

    Date earliest = least(least(a, b), c);
    

    Actually, you can make this a generic method for any Comparable:

    public static <T extends Comparable<T>> T least(T a, T b) {
        return a == null ? b : (b == null ? a : (a.compareTo(b) < 0 ? a : b));
    }