方法一:将要排序的对象类实现Comparable<>接口。
方法二:使用Comparator匿名内部类实现。
方法三:stream流
public class Student implements Comparable<Student >{
String name;
int age;
int score;
public Student(String name, int age, int score){
this.name=name;
this.age=age;
this.score=score;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", score=" + score +
'}';
}
@Override
public int compareTo(Student o) {
//根据年龄排序
return this.age - o.age;
}
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
students.add(new Student("AA", 1, 80));
students.add(new Student("BB", 4, 90));
students.add(new Student("CC", 3, 85));
students.add(new Student("DD", 1, 81));
//1、实现 Comparable<T>接口 根据年龄排序
System.out.println("1、实现 Comparable<T>接口 根据年龄排序");
Collections.sort(students);
for (Student s : students) {
System.out.println(s);
}
//2、使用Comparator匿名内部类实现。根据成绩排序
System.out.println("2、使用Comparator匿名内部类实现。根据成绩排序");
students.sort(new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
//根据成绩排序
return o1.score - o2.score;
}
});
for (Student s : students) {
System.out.println(s);
}
//3、stream流 年龄倒序Comparator.comparing(Student::getAge,Comparator.reverseOrder()) 年龄正序thenComparing(Student::getScore)
System.out.println("3、stream流 年龄倒序Comparator.comparing(Student::getAge,Comparator.reverseOrder()) 年龄倒序thenComparing(Student::getScore)");
List<Student> studentSortList1 = students.stream()
.sorted(
Comparator.comparing(Student::getAge,Comparator.reverseOrder())
.thenComparing(Student::getScore)
)
.collect(Collectors.toList());
for (Student s : studentSortList1) {
System.out.println(s);
}
//4.stream流
System.out.println("4.stream流");
List<Student> studentSortList2 = students.stream().sorted((o1, o2) -> Integer.compare(o1.getAge(), o2.getAge())).collect(Collectors.toList());
for (Student s : studentSortList2) {
System.out.println(s);
}
}
}
结果:
1、实现 Comparable<T>接口 根据年龄排序
Student{name='EE', age=12, score=81}
Student{name='FF', age=12, score=90}
Student{name='AA', age=13, score=80}
Student{name='DD', age=13, score=81}
Student{name='BB', age=14, score=90}
Student{name='CC', age=14, score=85}
2、使用Comparator匿名内部类实现。根据成绩排序
Student{name='AA', age=13, score=80}
Student{name='EE', age=12, score=81}
Student{name='DD', age=13, score=81}
Student{name='CC', age=14, score=85}
Student{name='FF', age=12, score=90}
Student{name='BB', age=14, score=90}
3、stream流 年龄倒序Comparator.comparing(Student::getAge,Comparator.reverseOrder()) 年龄倒序thenComparing(Student::getScore)
Student{name='CC', age=14, score=85}
Student{name='BB', age=14, score=90}
Student{name='AA', age=13, score=80}
Student{name='DD', age=13, score=81}
Student{name='EE', age=12, score=81}
Student{name='FF', age=12, score=90}
4.stream流
Student{name='EE', age=12, score=81}
Student{name='FF', age=12, score=90}
Student{name='AA', age=13, score=80}
Student{name='DD', age=13, score=81}
Student{name='CC', age=14, score=85}
Student{name='BB', age=14, score=90}