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?

183480 次浏览

你可以使用 Comparator.reverseOrder()有一个比较器,给出自然顺序的反向。

如果希望反转现有比较器的顺序,可以使用 Comparator.reversed()

示例代码:

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

也可以使用 比较器(函数,比较器)
必要时,链式比较器很方便,例如:

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

为什么不扩展现有的计算器并覆盖超级和也不结果。 Comperator Interface 的实现并不是必需的,但是它可以更清楚地说明发生了什么。

结果,您得到了一个易于重用的类文件,可测试的单元步骤和明确的 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;
}
}

我发现当你有一个自定义比较器和反向条件(你可以做或不做)时,这个问题搜索反向顺序。

匹诺曹提出的想法帮助了我。

这是密码:

int order = requestedOrder.equals("asc") ? 1 : -1;


Collections.sort(List<CustomObj>, new Comparator<CustomObj>() {
public int compare(CustomObj first, CustomObj scnd) {
return first.getComparableParam().compareTo(scnd.getComparableParam()) * order;
}
});

希望以后能帮到别人