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?
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));
Well, 'efficient' has some different meanings, but I don't think there will be an efficiency problem with comparing three dates. In fact, it's really cheap. You can try this approach:
SortedSet<Date> dates = new TreeSet<Date>();
dates.add(date1);
dates.add(date2);
// ...
dates.add(dateN);
Date earliest = dates.first();
Or, maybe more elegant:
for (Date date : someDates) {
if (date != null) {
dates.add(date);
}
}
Date earliest = dates.first();