Java流排序2变量升序/取消发送

我想排序seq1升序和seq2降序所以我这样做:

list = list.stream().sorted(comparing(AClass::getSeq1).thenComparing( AClass::getSeq2).reversed()).collect(toList()); 

但结果出来了,因为seq1和seq2都按降序排序。

我可以这样做以使seq1升序和seq2降序:

 sorted(comparing(AClass::getSeq1) .reversed().thenComparing(AClass::getSeq2).reversed() 

这是真正的正确方法吗?

在你的第一个例子中,reverse被应用于整个比较器,它比较seq1然后seq2按升序。

您需要的是仅反转第二个比较,例如,可以通过以下方式完成:

 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());