JDK8对List对象根据属性排序

文章目录

  • JDK8对List对象根据属性排序
  • [1. 被排序字段为null或者空时候报错](#1. 被排序字段为null或者空时候报错)
  • [2. 使用Stream流排序](#2. 使用Stream流排序)
    • [2.1 根据name升序](#2.1 根据name升序)
    • [2.2 根据name升序,score降序](#2.2 根据name升序,score降序)
  • [3. 使用Collections排序](#3. 使用Collections排序)
    • [3.1 根据name升序](#3.1 根据name升序)
    • [3.2 根据name升序,score降序](#3.2 根据name升序,score降序)
  • [4. 完整的demo](#4. 完整的demo)

JDK8对List对象根据属性排序

1. 被排序字段为null或者空时候报错

被排序字段为null或者空的时候报java.lang.NullPointerException

shell 复制代码
Exception in thread "main" java.lang.NullPointerException
	at java.util.Comparator.lambda$comparing$77a9974f$1(Comparator.java:469)
	at java.util.TimSort.countRunAndMakeAscending(TimSort.java:356)
	at java.util.TimSort.sort(TimSort.java:220)
	at java.util.Arrays.sort(Arrays.java:1512)
	at java.util.stream.SortedOps$SizedRefSortingSink.end(SortedOps.java:348)
	at java.util.stream.Sink$ChainedReference.end(Sink.java:258)
	at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:482)
	at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
	at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
	at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
	at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
	at com.stormkai.jh.ListSortDemo1.getNameAsc(ListSortDemo1.java:40)
	at com.stormkai.jh.ListSortDemo1.main(ListSortDemo1.java:19)

使用以下方式处理:

  • Comparator.nullsLast:排序字段为null的排在后面
  • Comparator.nullsFirst:排序字段为null的排在前面
  1. 集合工具类Collections
java 复制代码
Collections.sort(students1,Comparator.comparing(Student::getName,Comparator.nullsLast(String::compareTo)));
  1. stream流的方式
java 复制代码
List<Student> students1 = students.stream().map(student -> {
            if("".equals(student.getName())){
                student.setName(null);
            }
            return student;
        }).sorted(Comparator.comparing(Student::getName,Comparator.nullsLast(String::compareTo)))
                .collect(Collectors.toList())

2. 使用Stream流排序

Student.java

java 复制代码
@Data
@AllArgsConstructor
public class Student {
    private Integer id;
    private String name;
    private double score;
}

2.1 根据name升序

java 复制代码
public class ListSortDemo1 {
    public static void main(String[] args) {
        List<Student> students = new ArrayList<Student>(){{
            add(new Student(1,"张三C",98.50d));
            add(new Student(2,"张三B",67.50d));
            add(new Student(3,"张三A",85.40d));
            add(new Student(4,"",79.60d));
            add(new Student(5,null,84.80d));
            add(new Student(6,"张三D",95.20d));
        }};
        List<Student> students1 = getNameAsc(students);
        students1.forEach(System.out::println);
    }

    //按name升序,null和空的name都以null处理,排在最后
    private static List<Student> getNameAsc(List<Student> students) {
        List<Student> students1 = students.stream().map(student -> {
            if("".equals(student.getName())){
                student.setName(null);
            }
            return student;
        }).sorted(Comparator.comparing(Student::getName,Comparator.nullsLast(String::compareTo)))
                .collect(Collectors.toList());
        return students1;
    }
}

执行结果:

shell 复制代码
Student(id=3, name=张三A, score=85.4)
Student(id=2, name=张三B, score=67.5)
Student(id=1, name=张三C, score=98.5)
Student(id=6, name=张三D, score=95.2)
Student(id=4, name=null, score=79.6)
Student(id=5, name=null, score=84.8)

2.2 根据name升序,score降序

java 复制代码
//按name升序,按score降序,null和空的name都以null处理,排在最后
    private static List<Student> getNameAscAndScoreDesc(List<Student> students) {
        List<Student> students1 = students.stream().map(student -> {
            if("".equals(student.getName())){
                student.setName(null);
            }
            return student;
        }).sorted(Comparator.comparing(Student::getName,Comparator.nullsLast(String::compareTo)).reversed().thenComparing(Student::getScore).reversed())
                .collect(Collectors.toList());
        return students1;
    }

输出结果:

shell 复制代码
Student(id=3, name=张三A, score=85.4)
Student(id=2, name=张三B, score=67.5)
Student(id=1, name=张三C, score=98.5)
Student(id=6, name=张三D, score=95.2)
Student(id=5, name=null, score=84.8)
Student(id=4, name=null, score=79.6)

3. 使用Collections排序

3.1 根据name升序

java 复制代码
public class ListSortDemo1 {
    public static void main(String[] args) {
        List<Student> students = new ArrayList<Student>(){{
            add(new Student(1,"张三C",98.50d));
            add(new Student(2,"张三B",67.50d));
            add(new Student(3,"张三A",85.40d));
            add(new Student(4,"",79.60d));
            add(new Student(5,null,84.80d));
            add(new Student(6,"张三D",95.20d));
        }};
        //List<Student> students1 = getNameAsc(students);
        //List<Student> students1 = getNameAscAndScoreDesc(students);
        List<Student> students1 = getNameAsc1(students);
        students1.forEach(System.out::println);
    }

    private static List<Student> getNameAsc1(List<Student> students) {
        List<Student> students1 = students.stream().map(student -> {
            if ("".equals(student.getName())) {
                student.setName(null);
            }
            return student;
        }).collect(Collectors.toList());
        Collections.sort(students1,Comparator.comparing(Student::getName,Comparator.nullsLast(String::compareTo)));
        return students1;
    }
}

输出结果:

shell 复制代码
Student(id=3, name=张三A, score=85.4)
Student(id=2, name=张三B, score=67.5)
Student(id=1, name=张三C, score=98.5)
Student(id=6, name=张三D, score=95.2)
Student(id=4, name=null, score=79.6)
Student(id=5, name=null, score=84.8)

3.2 根据name升序,score降序

java 复制代码
private static List<Student> getNameAscAndScoreDesc1(List<Student> students) {
        List<Student> students1 = students.stream().map(student -> {
            if ("".equals(student.getName())) {
                student.setName(null);
            }
            return student;
        }).collect(Collectors.toList());
        Collections.sort(students1,Comparator.comparing(Student::getName,Comparator.nullsLast(String::compareTo)).reversed().thenComparing(Student::getScore).reversed());
        return students1;
    }

输出结果:

shell 复制代码
Student(id=3, name=张三A, score=85.4)
Student(id=2, name=张三B, score=67.5)
Student(id=1, name=张三C, score=98.5)
Student(id=6, name=张三D, score=95.2)
Student(id=5, name=null, score=84.8)
Student(id=4, name=null, score=79.6)

4. 完整的demo

java 复制代码
public class ListSortDemo1 {
    public static void main(String[] args) {
        List<Student> students = new ArrayList<Student>(){{
            add(new Student(1,"张三C",98.50d));
            add(new Student(2,"张三B",67.50d));
            add(new Student(3,"张三A",85.40d));
            add(new Student(4,"",79.60d));
            add(new Student(5,null,84.80d));
            add(new Student(6,"张三D",95.20d));
        }};
        //List<Student> students1 = getNameAsc(students);
        //List<Student> students1 = getNameAscAndScoreDesc(students);
        //List<Student> students1 = getNameAsc1(students);
        List<Student> students1 = getNameAscAndScoreDesc(students);
        students1.forEach(System.out::println);
    }

    //按name升序,null和空的name都以null处理,排在最后
    private static List<Student> getNameAsc(List<Student> students) {
        List<Student> students1 = students.stream().map(student -> {
            if("".equals(student.getName())){
                student.setName(null);
            }
            return student;
        }).sorted(Comparator.comparing(Student::getName,Comparator.nullsLast(String::compareTo)))
                .collect(Collectors.toList());
        return students1;
    }

    private static List<Student> getNameAsc1(List<Student> students) {
        List<Student> students1 = students.stream().map(student -> {
            if ("".equals(student.getName())) {
                student.setName(null);
            }
            return student;
        }).collect(Collectors.toList());
        Collections.sort(students1,Comparator.comparing(Student::getName,Comparator.nullsLast(String::compareTo)));
        return students1;
    }

    //按name升序,按score降序,null和空的name都以null处理,排在最后
    private static List<Student> getNameAscAndScoreDesc(List<Student> students) {
        List<Student> students1 = students.stream().map(student -> {
            if("".equals(student.getName())){
                student.setName(null);
            }
            return student;
        }).sorted(Comparator.comparing(Student::getName,Comparator.nullsLast(String::compareTo)).reversed()
                .thenComparing(Student::getScore).reversed())
                .collect(Collectors.toList());
        return students1;
    }

    private static List<Student> getNameAscAndScoreDesc1(List<Student> students) {
        List<Student> students1 = students.stream().map(student -> {
            if ("".equals(student.getName())) {
                student.setName(null);
            }
            return student;
        }).collect(Collectors.toList());
        Collections.sort(students1,Comparator.comparing(Student::getName,Comparator.nullsLast(String::compareTo)).reversed()
                .thenComparing(Student::getScore).reversed());
        return students1;
    }
}
相关推荐
儿时可乖了13 分钟前
使用 Java 操作 SQLite 数据库
java·数据库·sqlite
ruleslol15 分钟前
java基础概念37:正则表达式2-爬虫
java
xmh-sxh-131431 分钟前
jdk各个版本介绍
java
天天扭码1 小时前
五天SpringCloud计划——DAY2之单体架构和微服务架构的选择和转换原则
java·spring cloud·微服务·架构
程序猿进阶1 小时前
堆外内存泄露排查经历
java·jvm·后端·面试·性能优化·oom·内存泄露
FIN技术铺1 小时前
Spring Boot框架Starter组件整理
java·spring boot·后端
小曲程序1 小时前
vue3 封装request请求
java·前端·typescript·vue
陈王卜1 小时前
django+boostrap实现发布博客权限控制
java·前端·django
小码的头发丝、1 小时前
Spring Boot 注解
java·spring boot
java亮小白19971 小时前
Spring循环依赖如何解决的?
java·后端·spring