Arrays.asList(), Collections.min() and a null-safe comparator
LocalDate a = LocalDate.of(2025, Month.JANUARY, 6);
LocalDate b = null;
LocalDate c = LocalDate.of(2023, Month.NOVEMBER, 22);
List<LocalDate> dates = Arrays.asList(a, b, c);
LocalDate earliest =
Collections.min(
dates,
Comparator.nullsLast(Comparator.naturalOrder())
);
System.out.println("Earliest date: " + earliest);
I consider this both clear and short and simple, also compared to the stream solutions in a couple of other answers. Output is:
Earliest date: 2023-11-22
If all three dates happen to be null
, the output is:
Earliest date: null
Often we prefer List.of()
over Arrays.asList()
when passing each element; but since List.of()
does not accepts nulls, we can’t use it here.
Comparators are often used with sorting, but they are also very practical for just finding the minimum or maximum. My code does not perform any complete sort, it only finds the min according to the comparator.
Do use LocalDate
from java.time, the modern Java date and time API, for a date. The Date
class used in some of the answers had severe design problems and has been outdated the last 10 years (and counting).
The idea can obviously be used with any class that implements Comparable
and any number of objects of that class.