JDK8对List对象根据属性排序

文章目录

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

JDK8对List对象根据属性排序

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

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

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
Collections.sort(students1,Comparator.comparing(Student::getName,Comparator.nullsLast(String::compareTo)));
  1. stream流的方式
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

@Data
@AllArgsConstructor
public class Student {
    private Integer id;
    private String name;
    private double score;
}

2.1 根据name升序

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;
    }
}

执行结果:

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降序

//按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;
    }

输出结果:

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升序

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 students1 = getNameAsc(students);
        //List 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;
    }
}

输出结果:

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降序

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;
    }

输出结果:

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

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 students1 = getNameAsc(students);
        //List students1 = getNameAscAndScoreDesc(students);
        //List 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;
    }
}

你可能感兴趣的:(java,java)