Comparator.comparing()。reversed()反转所有较早的比较器?

Aas*_*war 4 java sorting list comparator

我有一个Triple列表,它是用户定义的类。当我使用Comparator它对它进行排序时,显示出奇怪的行为。

考虑一下此片段-

List<Triple> list = new ArrayList<>();
list.add(new Triple(1,12,13)); //adding values to list
list.add(new Triple(11,3,31));
list.add(new Triple(16,6,32));
list.add(new Triple(16,8,32));
list.add(new Triple(16,7,32));
list.add(new Triple(16,9,32));
list.add(new Triple(16,5,32));
list.add(new Triple(7,21,0));
list.add(new Triple(6,22,12));
list.add(new Triple(4,22,13));
list.add(new Triple(2,77,3));
list.add(new Triple(1,8,30));
Run Code Online (Sandbox Code Playgroud)

使用比较器排序

 list.sort(
 Comparator.comparingInt(Triple::getA)
.thenComparingInt(Triple::getB)
.thenComparing(Triple::getC));
 list.forEach(e->System.out.printf("(%d,%d,%d) ",e.getA(),e.getB(),e.getC()));
 System.out.println();
//sort A descending if for same A ascending B and for same B ascending C
 list.sort(
Comparator.comparingInt(Triple::getA).reversed()
.thenComparingInt(Triple::getB)
.thenComparing(Triple::getC));
 list.forEach(e->System.out.printf("(%d,%d,%d) ",e.getA(),e.getB(),e.getC()));
 System.out.println();
//sort A ascending if for same A descending B and for same B ascending C
list.sort(
Comparator.comparingInt(Triple::getA)
.thenComparingInt(Triple::getB)
.reversed()
.thenComparing(Triple::getC));
list.forEach(e->System.out.printf("(%d,%d,%d) ",e.getA(),e.getB(),e.getC()));
System.out.println();
//sort A ascending if for same A ascending B and for same B descending C
list.sort(
Comparator.comparingInt(Triple::getA)
.thenComparingInt(Triple::getB)
.thenComparing(Triple::getC)
.reversed());
list.forEach(e->System.out.printf("(%d,%d,%d) ",e.getA(),e.getB(),e.getC()));
Run Code Online (Sandbox Code Playgroud)

我希望输出如我在评论中所述的列表-

但是输出是


(16,5,32) (16,6,32) (16,7,32) (16,8,32) (16,9,32) (11,3,31) (7,21,0) (6,22,12) (4,22,13) (2,77,3) (1,8,30) (1,12,13)

(16,9,32) (16,8,32) (16,7,32) (16,6,32) (16,5,32) (11,3,31) (7,21,0) (6,22,12) (4,22,13) (2,77,3) (1,12,13) (1,8,30)

(16,9,32) (16,8,32) (16,7,32) (16,6,32) (16,5,32) (11,3,31) (7,21,0) (6,22,12) (4,22,13) (2,77,3) (1,12,13) (1,8,30)
Run Code Online (Sandbox Code Playgroud)

因此,reversed()方法可反转较早的比较器条件。

供您参考,Triple只是具有三个变量并获取set方法的类。

mic*_*alk 5

由于您定义了这样的比较器,Comparator.comparingInt(Triple::getA) .thenComparingInt(Triple::getB)因此将返回一个新的Comparator对象,该对象包含之前比较对象的两种方式。如果你再调用reversed这个Comparator返回新的比较可逆转此Comparator-所以在这种情况下,两个以前的条件将得到扭转。

如果要反转链中的一个比较器,则可以使用类似以下内容的方法:

.thenComparing(Triple::getB, Comparator.reverseOrder())
Run Code Online (Sandbox Code Playgroud)

因此,您的比较器之一可能类似于:

Comparator.comparingInt(Triple::getA)
                        .thenComparing(Triple::getB, Comparator.reverseOrder())
                        .thenComparing(Triple::getC)
Run Code Online (Sandbox Code Playgroud)

这只会颠倒B属性的排序条件。