代码语言:javascript复制
public class Student {
private int No;
private String name;
private int age;
private String address;
public int getNo() {
return No;
}
public void setNo(int no) {
No = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Student{"
"No=" No
", name='" name '''
", age=" age
", address='" address '''
'}';
}
}
代码语言:javascript复制public class Test {
public static void main(String[] args) {
Student s1 = new Student();
s1.setNo(1);
s1.setName("张三丰");
s1.setAge(18);
s1.setAddress("北京");
Student s2 = new Student();
s2.setNo(2);
s2.setName("刘能");
s2.setAge(18);
s2.setAddress("天津");
Student s3 = new Student();
s3.setNo(3);
s3.setName("王五");
s3.setAge(17);
s3.setAddress("上海");
Student s4 = new Student();
s4.setNo(4);
s4.setName("赵六");
s4.setAge(16);
s4.setAddress("深圳");
List<Student> list = new ArrayList<>();
list.add(s1);
list.add(s2);
list.add(s3);
list.add(s4);
//age 正序
Comparator<Student> byAgeAsc = Comparator.comparing(Student::getAge);
//No 倒叙
Comparator<Student> byNoDesc = Comparator.comparing(Student::getNo).reversed();
//name 正序
Comparator<Student> byName = Comparator.comparing(Student::getName);
//联合排序
Comparator<Student> finalComparator = byAgeAsc.thenComparing(byNoDesc).thenComparing(byName);
List<Student> collect = list.stream().sorted(finalComparator).collect(Collectors.toList());
System.out.println("多条件排序:" collect);
System.out.println("------排序结果:按照自定义排序");
List<Student> collect1 = list.stream().sorted(Comparator.comparing(Student::getAge).thenComparing(Student::getNo)).collect(Collectors.toList());
System.out.println("正序:" collect1);
System.out.println("------排序结果:age 正序,No 正序");
List<Student> collect2 = list.stream().sorted(Comparator.comparing(Student::getAge).thenComparing(Student::getNo).reversed()).collect(Collectors.toList());
System.out.println("整体结果倒叙返回:" collect2);
System.out.println("------排序结果:根据age 正序,No 正序的整体排序结果,倒叙返回。需要注意:返回结果不是age 正序,No 倒叙");
}
}
代码语言:javascript复制排序结果:
多条件排序:[Student{No=4, name='赵六', age=16, address='深圳'}, Student{No=3, name='王五', age=17, address='上海'}, Student{No=2, name='刘能', age=18, address='天津'}, Student{No=1, name='张三丰', age=18, address='北京'}]
------排序结果:按照自定义排序
正序:[Student{No=4, name='赵六', age=16, address='深圳'}, Student{No=3, name='王五', age=17, address='上海'}, Student{No=1, name='张三丰', age=18, address='北京'}, Student{No=2, name='刘能', age=18, address='天津'}]
------排序结果:age 正序,No 正序
整体结果倒叙返回:[Student{No=2, name='刘能', age=18, address='天津'}, Student{No=1, name='张三丰', age=18, address='北京'}, Student{No=3, name='王五', age=17, address='上海'}, Student{No=4, name='赵六', age=16, address='深圳'}]
------排序结果:根据age 正序,No 正序的整体排序结果,倒叙返回。需要注意:返回结果不是age 正序,No 倒叙