本文介绍了Java流排序2个变量升序/降序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想对 seq1 升序和 seq2 降序排序,所以我这样做:
I want to sort seq1 ascending and seq2 descending so I do this:
list = list.stream().sorted(comparing(AClass::getSeq1).thenComparing(
AClass::getSeq2).reversed()).collect(toList());
但是结果出来是因为 seq1 和 seq2 都是按降序排序的.
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:
sorted(comparing(AClass::getSeq1)
.reversed().thenComparing(AClass::getSeq2).reversed()
真正正确的方法是什么?
What is really the correct way to do this?
推荐答案
在您的第一个示例中,reversed
应用于整个比较器,它按升序比较 seq1 然后 seq2.
In your first example, reversed
is applied to the whole comparator which compares seq1 then seq2 in ascending order.
您只需要反转第二个比较,例如,可以这样做:
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());
这篇关于Java流排序2个变量升序/降序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!