Sort Java collection relative to the current date

  • A+
Category:Languages

I want to sort my List of Date relative to the current date, e.g we have next items in list:

10.01.2018,  10.20.2018,  10.14.2018,  10.02.2018  

and the current date is 10.08.2018.

The result should be ascending sort of array in the next order:

10.14.2018,  10.20.2018    and then  10.01.2018,  10.02.2018.  

First should be dates that didn't happen and then the past dates. How to do it with Comparator?

 


You can see this way

  • if the two dates you're comparing are on the same side (both before or both after) of today, compare them normally
  • if you have one before and one after you need to reverse the order

This will keep ascending order but put future dates before past dates

public static void main(String[] args) {     List<LocalDate> list = Arrays.asList(                                       LocalDate.of(2018, 10, 1), LocalDate.of(2018, 10, 20),                                       LocalDate.of(2018, 10, 14),LocalDate.of(2018, 10, 2));     System.out.println(list);     LocalDate now = LocalDate.now();      list.sort((o1, o2) -> {         if (o1.isBefore(now) && o2.isBefore(now) || o1.isAfter(now) && o2.isAfter(now)) {             return o1.compareTo(o2);         }         return o2.compareTo(o1);     });      System.out.println(list); }   [2018-10-01, 2018-10-20, 2018-10-14, 2018-10-02] [2018-10-14, 2018-10-20, 2018-10-01, 2018-10-02] 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: