Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort Java collection relative to the current date

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?

like image 863
koflox Avatar asked Oct 08 '18 14:10

koflox


People also ask

How do you sort objects based on date?

Inside the compare method for return value use the compareTo() method which will return the specified value by comparing the DateItem objects. Now in the main method use Collections. sort() method and pass the ArrayList and 'SortItem' class object to it, it will sort the dates, and output will be generated.

How do you sort collections in Java?

The sorted() Method in Java The sorted() method used to sort the list of objects or collections of the objects in the ascending order. If the collections of the objects are comparable then it compares and returns the sorted collections of objects; otherwise it throws an exception from java. lang.

How do you sort a list of objects based on an attribute of the objects in Java?

In the main() method, we've created an array list of custom objects list, initialized with 5 objects. For sorting the list with the given property, we use the list's sort() method. The sort() method takes the list to be sorted (final sorted list is also the same) and a comparator.


2 Answers

The most concise and elegant, yet readable way I've found is as follows:

list.sort(
    Comparator
    .comparing( LocalDate.now()::isAfter )
    .thenComparing( Comparator.naturalOrder() )
);

This reads as sort by first comparing whether each date is after today or not, then break ties using LocalDate's natural order. (It's worth remembering that sorting boolean values means putting falses at the beginning and trues at the end, i.e. false < true).

like image 128
fps Avatar answered Sep 17 '22 23:09

fps


    LocalDate now = LocalDate.now();

    List<LocalDate> dates = Arrays.asList(
            LocalDate.parse("2018-10-02"),
            LocalDate.parse("2018-10-20"),
            LocalDate.parse("2018-10-14"),
            LocalDate.parse("2018-10-01"));

    // sort relative to the current date
    dates.sort(Comparator.<LocalDate>comparingInt(localDate ->
            localDate.isAfter(now) ? -1 : localDate.isBefore(now) ? 1 : 0)
            // then sort normally
            .thenComparing(Comparator.naturalOrder()));

    System.out.println(dates);
like image 38
Alexander Pankin Avatar answered Sep 18 '22 23:09

Alexander Pankin