Cethy Cethy - 6 months ago 21
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:

date1.before(date2);


or

date2.after(date1);


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?

Answer

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));

Then:

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

etc.

Comments