Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the earliest date among 3 dates

Tags:

java

date

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?

like image 719
Ace Avatar asked Apr 04 '13 20:04

Ace


2 Answers

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));
}
like image 188
Bohemian Avatar answered Sep 20 '22 14:09

Bohemian


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));
like image 23
pavelety Avatar answered Sep 21 '22 14:09

pavelety