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

真正正确的方法是什么?


问题答案:

在第一个示例中,reversed将其应用于整个比较器,该比较器按升序比较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());