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?
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With