java 逆向排序_java – 是否可以使用Comparator.comparingInt链以反向自然顺序对两个字段进行排序...

假设我想在字段高度上以相反的顺序对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

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值