Java8-使用stream.sorted()对List排序

文章介绍了Java中流(Stream)的概念,展示了如何使用Comparator对集合进行排序,包括按照自定义属性(如年龄和分数)的升序和降序排列。同时,文章讨论了当分数字段为BigDecimal类型时的排序处理,以及如何处理null值的情况。

1.流的定义

Stream 中文称为 “流”,通过将集合转换为这么一种叫做 “流” 的元素序列,通过声明性方式,能够对集合中的每个元素进行一系列并行或串行的操作!
如果流中的元素的类实现了 Comparable 接口,即有自己的排序规则,那么可以直接调用 sorted() 方法对元素进行排序!

2.源码实现

import lombok.Data;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * @author yangl
 * @version V1.0
 * @date 2023-02-28 14:51
 */
@Data
public class User {

    private String name;
    //age
    private int age;
    //分数
    private double fraction;

    public User(String name, int age, double fraction) {
        this.name = name;
        this.age = age;
        this.fraction = fraction;
    }

    public static void main(String[] args) {
        List<User> userList = new ArrayList<>();
        userList.add(new User("allan1", 22, 2.2));
        userList.add(new User("allan2", 22, 2.5));
        userList.add(new User("allan3", 40, 2.7));
        userList.add(new User("allan4", 45, 2.8));

        //返回 对象集合以Age升序排序:年龄   --默认升序
        userList.stream().sorted(Comparator.comparing(User::getAge));

        //返回 对象集合以Age降序排序  
        userList.stream().sorted(Comparator.comparing(User::getAge).reversed()); //排序结果后再排序,
        //等效写法
        userList.stream().sorted(Comparator.comparing(User::getAge, Comparator.reverseOrder()));//是直接进行排序

        //返回 对象集合以Age升序排序并返回前n个元素  --默认升序  
        userList.stream().sorted(Comparator.comparing(User::getAge)).limit(2);

        //返回 对象集合以Age升序排序并去除前 n 个元素 --默认升序 
        userList.stream().sorted(Comparator.comparing(User::getAge)).skip(2);

        //返回 对象集合以Age升序 getFraction升序
        userList.stream().sorted(Comparator.comparing(User::getAge).thenComparing(User::getFraction));

        //先以getAge升序,升序结果进行getAge降序,再进行getFraction升序
        userList.stream().sorted(Comparator.comparing(User::getAge).reversed().thenComparing(User::getFraction));

        //先以getAge降序,再进行getFraction升序
        userList.stream().sorted(Comparator.comparing(User::getAge, Comparator.reverseOrder()).thenComparing(User::getFraction));

        //先以getAge升序,升序结果进行getAge降序,再进行getFraction降序
        userList.stream().sorted(Comparator.comparing(User::getAge).reversed().thenComparing(User::getFraction, Comparator.reverseOrder()));

        //先以getAge降序,再进行getFraction降序
        userList.stream().sorted(Comparator.comparing(User::getAge, Comparator.reverseOrder()).thenComparing(User::getFraction, Comparator.reverseOrder()));


        //先以getAge升序,升序结果进行getAge降序,再进行getFraction升序,结果进行getAge降序getFraction降序
        userList.stream().sorted(Comparator.comparing(User::getAge).reversed().thenComparing(User::getFraction).reversed());

        //先以getAge升序,再进行getFraction降序
        userList.stream().sorted(Comparator.comparing(User::getAge).thenComparing(User::getFraction, Comparator.reverseOrder()));
    }

}

3.总结

//这里的dtoLists是需要自己放入一些数据的
List<CurrentAndHistoryPerformanceDto> dtoLists = new ArrayList<>();
dtoLists.sort(Comparator.comparing(CurrentAndHistoryPerformanceDto::getMetricType).
                thenComparing(CurrentAndHistoryPerformanceDto::getStartTime));
//等效于
dtoLists = dtoLists.stream().sorted(Comparator.comparing(CurrentAndHistoryPerformanceDto::getMetricType).
                thenComparing(CurrentAndHistoryPerformanceDto::getStartTime)).
				collect(Collectors.toList());

4.提出问题,若fraction(分数)是BigDecimal 类型呢

....
...
...
private BigDecimal fraction;
//其他部分代码保持一致,仅仅是分数是BigDecimal 类型
...
...
...

5.代码实例

//按年龄排序后,再按分数排序
List<User> list = list.stream()
        .sorted(Comparator.comparing(User::getAge)
                .thenComparing(User::getFraction))
        .collect(Collectors.toList());
//按分数排序,排序时过滤Null值(如果排序的字段为null,NPE)
List<User> list = list.stream()
        .filter(c -> Objects.nonNull(c.getFraction()))
        .sorted(Comparator.comparing(User::getFraction))
        .collect(Collectors.toList());
//按分数排序,Null值排在最前面
List<User> list = list.stream()
        .sorted(Comparator.comparing(User::getFraction,
                Comparator.nullsFirst(BigDecimal::compareTo)))
        .collect(Collectors.toList());
//注意Comparator.nullsFirst的方法引用中,比较的字段是BigDecimal类型的,如果前后类型不一致,会报错:Non-static method cannot be referenced from a static context
//按分数排序,Null值排在最后面
List<User> list = list.stream()
        .sorted(Comparator.comparing(User::getFraction,
                Comparator.nullsLast(BigDecimal::compareTo)))
        .collect(Collectors.toList());

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值