Java中lambda和stream实现排序

在日常开发中,对数据排序是非常常见的一种需求,一般通过如下两种方式:

  • 存储系统:通过SQL、NoSQL的排序功能,查询的结果是完成排序的结果;
  • 内存:通过在内存中进行排序,查询的结果是无序的结果;

下面聊聊通过Java中的lambda和stream实现在内存中对数据进行排序。

1、定义一个基础类

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student {

    private String name;
    private int age;

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        Student student = (Student) o;
        return age == student.age && Objects.equals(name, student.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }
}

2、使用Comparator排序

	@Test
    void test() {
        List<Student> students = Lists.newArrayList(
                new Student("caocao", 21),
                new Student("sunquan", 20)
        );

        Collections.sort(students, new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                return o1.getName().compareTo(o2.getName());
            }
        });
        Assertions.assertEquals(students.get(0), new Student("caocao", 21));
    }

在定义的Comparator中使用name字段排序,string类型的排序是通过ASCII码顺序进行判断。
3、使用lambda排序

	@Test
    void test() {
        List<Student> students = Lists.newArrayList(
                new Student("caocao", 21),
                new Student("sunquan", 20)
        );

        students.sort((o1, o2) -> o1.getName().compareTo(o2.getName()));
        Assertions.assertEquals(students.get(0), new Student("caocao", 21));
    }

将内部类Comparator替换为lambda表达式,使代码更简洁。
4、使用Comparator的comparing方法排序

	@Test
    void test() {
        List<Student> students = Lists.newArrayList(
                new Student("caocao", 21),
                new Student("sunquan", 20)
        );

        students.sort(Comparator.comparing(Student::getName));
        Assertions.assertEquals(students.get(0), new Student("caocao", 21));
    }

5、自定义比对方法
在Student类中自定义比对方法

	public static int compareByNameThenAge(Student s1, Student s2) {
        if (s1.name.equals(s2.name)) {
            return Integer.compare(s1.age, s2.age);
        } else {
            return s1.name.compareTo(s2.name);
        }
    }

先比对name,再比对age

	@Test
    void test() {
        List<Student> students = Lists.newArrayList(
                new Student("caocao", 21),
                new Student("sunquan", 20)
        );

        students.sort((o1,o2) -> Student.compareByNameThenAge(o1,o2));
        Assertions.assertEquals(students.get(0), new Student("caocao", 21));
    }

6、使用stream排序
在流式计算时进行排序

	@Test
    void test() {
        List<Student> students = Lists.newArrayList(
                new Student("caocao", 21),
                new Student("sunquan", 20)
        );

        List<Student> result = students.stream().sorted(new Comparator<Student>() {
            @Override
            public int compare(Student o1, Student o2) {
                return o1.getName().compareTo(o2.getName());
            }
        }).collect(Collectors.toList());
        
        Assertions.assertEquals(result.get(0), new Student("caocao", 21));
    }

7、null值判断
若列表中元素是null或列表中元素参与排序的字段是null,会出现NullPointException异常,即 NPE,简单演示一下:

	@Test
    void sortedNullGotNPE() {
        List<Student> students = Lists.newArrayList(
                null,
                new Student("liubei", 12)
        );
        students.sort(Comparator.comparing(Student::getName));
    }

修改为

	@Test
    void sortedNullGotNPE() {
        List<Student> students = Lists.newArrayList(
                null,
                new Student("liubei", 12)
        );
        //students.sort(Comparator.comparing(Student::getName));

        Assertions.assertThrows(NullPointerException.class,
                () -> students.sort(Comparator.comparing(Student::getName)));
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值