参考:
总结——》【Java】
import lombok.Data;
import lombok.experimental.Accessors;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<Student> list = new Student().getStudentList();
//id升序
list.sort(Comparator.comparing(Student::getId));
//id降序
list.sort(Comparator.comparing(Student::getId).reversed());
//多条件升序
list.sort(Comparator.comparing(Student::getId).thenComparing(Student::getAge));
//id降序,age升序
list.sort(Comparator.comparing(Student::getId).reversed().thenComparing(Student::getAge));
//age升序
Collections.sort(list, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.getAge() - o2.getAge();
}
});
//age降序
Collections.sort(list, (Student s1, Student s2) -> s2.getAge().compareTo(s1.getAge()));
}
@Data
@Accessors(chain = true)
static class Student {
public Integer id;
public Integer age;
public List<Student> getStudentList() {
List<Student> studentList = new ArrayList<>();
studentList.add(new Student().setId(1).setAge(10));
studentList.add(new Student().setId(2).setAge(5));
studentList.add(new Student().setId(3).setAge(15));
studentList.add(new Student().setId(3).setAge(5));
return studentList;
}
}
}