假设我想在字段高度上以相反的顺序对ArrayList中的对象进行排序,如果两个值相同,我还想以相反的顺序对字段宽度进行进一步排序.

有没有办法使用类似的东西

Comparator comparator = Comparator

.comparingInt((Test t) -> t.height).reversed()

.thenComparingInt((Test t ) -> t.width).reversed();

我知道我可以使用类似的东西:

Collections.sort(list, new Comparator() {

public int compare(Test o1, Test o2) {

Integer x1 = o1.height;

Integer x2 = o2.height;

int sComp = x2.compareTo(x1);

if (sComp != 0) {

return sComp;

}

x1 = o1.width;

x2 = o2.width;

return x2.compareTo(x1);

}});

但是,如果有一个解决方案,我真的很好奇

所以关于这个迷你的例子

import java.util.ArrayList;

import java.util.Comparator;

import java.util.List;

public class Main {

public static void main(String[] args) {

Test one = new Test();

one.height = 2;

one.width = 1;

Test two = new Test();

two.height = 2;

two.width = 3;

Test three = new Test();

three.height = 1;

three.width = 1;

Comparator comparator = Comparator

.comparingInt((Test t) -> t.height).reversed()

.thenComparingInt((Test t ) -> t.width).reversed();

List list = new ArrayList<>();

list.add(one);

list.add(two);

list.add(three);

list.stream()

.sorted(comparator)

.forEach(e -> System.out.println(e.height + "/" + e.width));

}

}

class Test {

int width;

int height;

}

我得到输出:

1/1

2/3

2/1

因为第二个reverse()会反转整个列表.

有没有办法产生以下输出:

2/3

2/1

1/1

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐