view raw
Cethy Cethy - 11 months ago 46
Java Question

Compare a Date with three or more Date(s) in Java 8?

With the java.time API it is possible to compare two dates using the following syntax:




This however becomes very verbose when comparing 3 or more dates.
Is there a way of comparing a Date with multiple others, to see if the one provided is before/after all the other ones?


All you're trying to do here is to compare the date to just one of your "3 or more" dates: you just have to work out which one that is, and then compare two dates.

Since Date implements Comparable<Date>, you can use Collections.min and Collections.max to find the earliest and latest of them:

Date earliest = Collections.min(Arrays.asList(date1, date2, date3));
Date latest   = Collections.max(Arrays.asList(date1, date2, date3));


boolean beforeEarliest = date.before(earliest);
boolean afterLatest    = date.after(latest);