复杂对象的List的排序写法,含stream写法

需求:
对象的list按照对象的某个属性进行排序

示例对象:

 @Data
class txcClass{
     private String name;
     private int age;

     public txcClass(String name, int age) {
         this.name = name;
         this.age = age;
     }

     @Override
     public String toString() {
         return "txcClass{" +
                 "name='" + name + '\'' +
                 ", age=" + age +
                 '}';
     }
 }

非stream写法:

// 初始化数据
List<txcClass> list = new ArrayList<>();
txcClass z3 = new txcClass("z3", 10);
txcClass l4 = new txcClass("l4", 20);
txcClass w5 = new txcClass("w5", 4);
list.add(z3);
list.add(l4);
list.add(w5);

//升序排列(降序把o1,o2调个位置)
 Collections.sort(list, new Comparator<txcClass>() {
     @Override
     public int compare(txcClass o1, txcClass o2) {
         return o1.getAge()-(o2.getAge());
     }
 });

stream写法:

//升序排列(降序把o1,o2调个位置)
List<txcClass> collect = list.stream().sorted((o1, o2) -> o1.getAge() - o2.getAge()).collect(Collectors.toList());
//上面同时等效于下面的写法(只有升序时等效,降序是不等效的)
List<txcClass> collect = list.stream().sorted(Comparator.comparingInt(txcClass::getAge)).collect(Collectors.toList());
        

collect.stream().forEach(b->{
    System.out.println(b.toString());
});

降序排列的另一个写法

List<txcClass> collect = list.stream().sorted(Comparator.comparingInt(txcClass::getAge).reversed()).collect(Collectors.toList());

引申:
上述是对整个List进行排序,那如果我们只想按照txcClass的age排序,然后只返回name的集合,该如何操作呢?
此时使用stream操作更简便

List<String> collect = list.stream().sorted((o1, o2) -> o2.getAge() - o1.getAge())
           .map(txcClass::getName)
           .collect(Collectors.toList());

取前5条

List<txcClass> collect = list.stream().sorted(Comparator.comparingInt(txcClass::getAge).reversed()).limit(5).collect(Collectors.toList());
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值