数字排序
List<Student> students = new ArrayList<>();
Student student1 = new Student("六年级","Math","小张",1D);
students.add(student1);
Student student2 = new Student("三年级上","English","小钱",8D);
students.add(student2);
Student student3 = new Student("五年级","Chinese","小孙",6D);
students.add(student3);
倒序
List<Student> collect = students.stream().sorted(Comparator.comparing(Student::getMark).reversed()).collect(Collectors.toList());
控制台:
排序前:1.0|8.0|6.0|
排序后:8.0|6.0|1.0|
正序
List<Student> collect = students.stream().sorted(Comparator.comparing(Student::getMark)).collect(Collectors.toList());
控制台:
排序前:1.0|8.0|6.0|
排序后:1.0|6.0|8.0|
以中文排序
List<Student> students = new ArrayList<>();
Student student1 = new Student("六年级","Math","小张",1D);
students.add(student1);
Student student2 = new Student("三年级上","English","小钱",8D);
students.add(student2);
Student student3 = new Student("五年级","Chinese","小孙",6D);
students.add(student3);
List<Student> collect = students.stream().sorted(Comparator.comparing(Student::getGrade).reversed()).collect(Collectors.toList());
控制台:
排序前:六年级|三年级上|五年级|
排序后:六年级|五年级|三年级上|
List<Student> collect = students.stream().sorted(Comparator.comparing(Student::getGrade)).collect(Collectors.toList());
控制台:
排序前:六年级|三年级上|五年级|
排序后:三年级上|五年级|六年级|
排序字段为null时
List<Student> students = new ArrayList<>();
Student student1 = new Student("六年级","Math","小张",1D);
students.add(student1);
Student student2 = new Student("三年级上","English","小钱",8D);
students.add(student2);
Student student3 = new Student(null,"Chinese","小孙",6D);
students.add(student3);
List<Student> collect = students.stream().sorted(Comparator.comparing(Student::getGrade).reversed()).collect(Collectors.toList());
控制台:
Exception in thread "main" java.lang.NullPointerException
at java.lang.String.compareTo(String.java:1155)
at java.lang.String.compareTo(String.java:111)
at java.util.Comparator.lambda$comparing$77a9974f$1(Comparator.java:469)
at java.util.Collections$ReverseComparator2.compare(Collections.java:5185)
at java.util.TimSort.countRunAndMakeAscending(TimSort.java:360)
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.AbstractPipeline.copyInto(AbstractPipeline.java:483)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:472)
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.hbis.ttie.mal.rest.Test2.main(Test2.java:29)
|