java Java流排序2个变量升序/降序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30382453/
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
Java stream sort 2 variables ascending/desending
提问by Bruce
I want to sort seq1 ascending and seq2 descending so I do this:
我想对 seq1 升序和 seq2 降序进行排序,所以我这样做:
list = list.stream().sorted(comparing(AClass::getSeq1).thenComparing(
AClass::getSeq2).reversed()).collect(toList());
But the result come out as both seq1 and seq2 are sorted in descending order.
但结果是 seq1 和 seq2 都按降序排序。
I can do this to make seq1 ascending and seq2 descending:
我可以这样做使 seq1 升序和 seq2 降序:
sorted(comparing(AClass::getSeq1)
.reversed().thenComparing(AClass::getSeq2).reversed()
What is really the correct way to do this?
真正做到这一点的正确方法是什么?
回答by assylias
In your first example, reversed
is applied to the whole comparator which compares seq1 then seq2 in ascending order.
在您的第一个示例中,reversed
应用于整个比较器,该比较器按升序比较 seq1 和 seq2。
What you need is to reverse the second comparison only, which can be done, for example, with:
您需要做的是仅反转第二个比较,这可以完成,例如:
import static java.util.Collections.reverseOrder;
import static java.util.Comparator.comparing;
list = list.stream().sorted(
comparing(AClass::getSeq1)
.thenComparing(reverseOrder(comparing(AClass::getSeq2))))
.collect(toList());
//or you could also write:
list = list.stream().sorted(
comparing(AClass::getSeq1)
.thenComparing(comparing(AClass::getSeq2).reversed()))
.collect(toList());