Java中的lambda和stream实现排序

2022-11-13 17:11:01 lambda java 排序

前言

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

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

下面聊聊通过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)));
    }

到此这篇关于Java中的lambda和stream实现排序的文章就介绍到这了,更多相关Java lambda和stream 内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关文章