java list 多字段 排序_Java 集合多字段排序

@Data

@AllArgsConstructor

public class Person {

Integer id;

Integer age;

Integer type;

public static void main(String[] args) {

List persons = new ArrayList<>();

persons.add(new Person(7, 10, 1));

persons.add(new Person(2, 10, 1));

persons.add(new Person(5, 10, 1));

persons.add(new Person(3, 26, 2));

persons.add(new Person(4, 35, 2));

persons.add(new Person(6, 23, 2));

persons.add(new Person(10, 23, 3));

persons.add(new Person(11, 24, 3));

persons.add(new Person(11, 23, 3));

persons = persons.stream()

.sorted(

Comparator.comparing(Person::getType).reversed()

.thenComparing(Person::getId)

.thenComparing(Comparator.comparing(Person::getAge).reversed())

).collect(Collectors.toList());

System.out.println(JSON.toJSONString(persons));

}

}

上面的代码,先对 type 降序, 再对 id 升序,最后对 age 降序。输出结果如下:

persons: [{"age":10,"id":7,"type":1},{"age":10,"id":2,"type":1},{"age":10,"id":5,"type":1},{"age":26,"id":3,"type":2},{"age":35,"id":4,"type":2},{"age":23,"id":6,"type":2},{"age":23,"id":10,"type":3},{"age":24,"id":11,"type":3},{"age":23,"id":11,"type":3}]

result: [{"age":23,"id":10,"type":3},{"age":24,"id":11,"type":3},{"age":23,"id":11,"type":3},{"age":26,"id":3,"type":2},{"age":35,"id":4,"type":2},{"age":23,"id":6,"type":2},{"age":10,"id":2,"type":1},{"age":10,"id":5,"type":1},{"age":10,"id":7,"type":1}]

上面的例子,是以为要输出原集合和结果集合,所有才用stream做演示,如果仅仅只是需要对列表做排序,可直接用List#sort(Comparator super E> c)方法。

站在巨人肩膀上摘苹果

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值