Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse a comparator in Java 8

I have an ArrayList and want sort it in descending order. I use for it java.util.stream.Stream.sorted(Comparator) method. Here is a description according Java API:

Returns a stream consisting of the elements of this stream, sorted according to the provided Comparator.

this methods return me a sort with ascending order. Which parameter should I change, just to have the descending order?

like image 458
Guforu Avatar asked Oct 07 '15 14:10

Guforu


People also ask

How do you reverse a comparator in Java?

You can use Comparator. reverseOrder() to have a comparator giving the reverse of the natural ordering. If you want to reverse the ordering of an existing comparator, you can use Comparator. reversed() .

How do you sort a comparator in Java 8?

naturalOrder(), which returns a Comparator that sorts by placing capital letters first, and String. CASE_INSENSITIVE_ORDER, which returns a case-insensitive Comparator. Basically, in Java 7, we were using Collections. sort() that was accepting a List and, eventually, a Comparator – in Java 8 we have the new List.


1 Answers

You can use Comparator.reverseOrder() to have a comparator giving the reverse of the natural ordering.

If you want to reverse the ordering of an existing comparator, you can use Comparator.reversed().

Sample code:

Stream.of(1, 4, 2, 5)     .sorted(Comparator.reverseOrder());      // stream is now [5, 4, 2, 1]  Stream.of("foo", "test", "a")     .sorted(Comparator.comparingInt(String::length).reversed());      // stream is now [test, foo, a], sorted by descending length 
like image 86
Tunaki Avatar answered Oct 07 '22 09:10

Tunaki