对集合排序,多字段排序(升序和降序)(空值排到最后)
数据准备 排序
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = false)
public class Student {
private Long id;
private String name;
private int classNum;
}
import com.alibaba.fastjson.JSON;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class SortTest {
public static void main(String[] args) {
Student student4 = new Student();
//student4.setId("4");
student4.setName("4");
student4.setClassNum(4);
Student student5 = new Student();
student5.setId(66l);
student5.setName("5");
student5.setClassNum(4);
Student student1 = new Student();
student1.setId(11l);
student1.setName("5");
student1.setClassNum(4);
Student student2 = new Student();
student2.setId(44l);
student2.setName("5");
student2.setClassNum(4);
Student student3 = new Student();
student3.setId(334l);
student3.setName("5");
student3.setClassNum(4);
Student student6 = new Student();
student6.setId(44L);
student6.setName("4");
student6.setClassNum(3);
List<Student> list2 = new ArrayList();
list2.add(student4);
list2.add(student5);
list2.add(student6);
list2.add(student1);
list2.add(student2);
list2.add(student3);
System.out.println(list2);
List list3 = list2.stream().sorted(Comparator.comparing(Student::getId,Comparator.nullsFirst(Long::compareTo)).reversed())
.collect(Collectors.toList());
//倒叙
String s1 = JSON.toJSONString(list3);
System.out.println(s1);
List list4 = list2.stream().sorted(Comparator.comparing(Student::getId,Comparator.nullsLast(Long::compareTo)))
.collect(Collectors.toList());//升序
List list5 = list2.stream().sorted(Comparator.comparing(Student::getId,Comparator.nullsLast(Long::compareTo))
.reversed().thenComparing(Student::getName,Comparator.nullsLast(String::compareTo)))
.collect(Collectors.toList());//id降序,名字升序
String s2 = JSON.toJSONString(list4);
System.out.println(s2);
String s3 = JSON.toJSONString(list5);
System.out.println(s3);
}