反转 Java 8 中的比较器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32995559/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 14:08:23  来源:igfitidea点击:

Reverse a comparator in Java 8

javasortingjava-8comparatorjava-stream

提问by Guforu

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:

我有一个 ArrayList 并希望按降序对其进行排序。我使用它的java.util.stream.Stream.sorted(Comparator)方法。下面是根据 Java API 的描述:

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

返回由该流的元素组成的流,根据提供的 进行排序Comparator

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

这个方法返回一个升序排序。我应该更改哪个参数,只是为了降序?

采纳答案by Tunaki

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

您可以使用Comparator.reverseOrder()比较器给出与自然顺序相反的顺序。

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

如果要颠倒现有比较器的顺序,可以使用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

回答by Dici

回答by dim42

You can also use Comparator.comparing(Function, Comparator)
It is convenient to chain comparators when necessary, e.g.:

也可以使用Comparator.comparing(Function, Comparator)
必要时链式比较器很方便,例如:

Comparator<SomeEntity> ENTITY_COMPARATOR = comparing(SomeEntity::getProperty1, reverseOrder())
        .thenComparingInt(SomeEntity::getProperty2)
        .thenComparing(SomeEntity::getProperty3, reverseOrder());

回答by Pinocchio

Why not to extend the existing comperator and overwrite super and nor the result. The implementation the Comperator Interface is not nessesery but it makes it more clear what happens.

为什么不扩展现有的比较器并覆盖 super 和结果。Comperator Interface 的实现并不重要,但它使发生的事情变得更加清楚。

In result you get a easy reusable Class File, testable unit step and clear javadoc.

结果,您将获得一个简单的可重用类文件、可测试的单元步骤和清晰的 javadoc。

public class NorCoperator extends ExistingComperator implements Comparator<MyClass> {
    @Override
    public int compare(MyClass a, MyClass b) throws Exception {
        return super.compare(a, b)*-1;
    }
}