Reverse a comparator in Java 8

2019-01-09 08:48发布

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?

2条回答
狗以群分
2楼-- · 2019-01-09 09:18

You can use Comparator.reverseOrder() to have a comparator that imposes 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
查看更多
霸刀☆藐视天下
3楼-- · 2019-01-09 09:30
登录 后发表回答