對任意類型集合對象進行整體排序,排序時將此接口的實現傳遞給Collections.sort方法或者Arrays.sort方法排序.
實現int compare(T o1, T o2);方法,返回正數,零,負數各代表大於,等於,小於。
用於排序的示例代碼如下:
實體類:Student
package com.zjx;
public class Student {
private String username;
private int age;
public Student(String username, int age) {
this.username = username;
this.age = age;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
用於排序的list集合
List<Student> students = new ArrayList<Student>() {{
add(new Student("張三", 12));
add(new Student("張三", 13));
add(new Student("張三", 34));
add(new Student("李四", 54));
add(new Student("李四", 12));
add(new Student("王五", 23));
add(new Student("王五", 21));
}};
方法一
//升序
Collections.sort(students, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.getAge() - o2.getAge();
}
});
//降序
Collections.sort(students, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o2.getAge() - o1.getAge();
}
});
方法二
升序
Collections.sort(students,(o1,o2) ->(o1.getAge()-o2.getAge()));
降序
Collections.sort(students,(o1,o2) ->(o2.getAge()-o1.getAge()));
方法三
Java8實現方式
Comparator<Student> comparator = Comparator.comparing(Student::getAge);
//升序
List<Student> list = students.stream().sorted(comparator).collect(Collectors.toList());
//倒序
List<Student> list = students.stream().sorted(comparator.reversed()).collect(Collectors.toList());