Find the earliest date among 3 dates

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));
}

Java 8+ oneliner. To make it safe, null check is added. Pass any number of dates.

public static Date min(Date... dates) {
    return Arrays.stream(dates).filter(Objects::nonNull).min(Date::compareTo).orElse(null);
}

Not null safe, but much shorter:

public static Date min(Date... dates) {
    return Collections.min(Arrays.asList(dates));
}

Not null safe without a new method:

Collections.min(Arrays.asList(date1, date2));

Tags:

Java

Date