使用前提:
Map
,Set
,List
等集合中,他们都提共了一个排序方法 sort()
,要对数据排序直接使用这个方法就行,但是要保证集合中的对象是 可比较的。
通过对该对象实现 Comparable<T>
接口实现对象可比较的。然后重写里面的compareTo()
方法。
代码举例说明:
假设我们有一个学生类,默认需要按学生的年龄字段 age
进行排序 代码如下:
public class Student implements Comparable<Student> {
private int id;
private int age;
private String name;
public Student(int id, int age, String name) {
this.id = id;
this.age = age;
this.name = name;
}
@Override
public int compareTo(Student o) {
//降序
//return o.age - this.age;
//升序
return this.age - o.age;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", age=" + age +
", name='" + name + '\'' +
'}';
}
}
public static void main(String args[]){
List<Student> list = new ArrayList<>();
list.add(new Student(1,25,"关羽"));
list.add(new Student(2,21,"张飞"));
list.add(new Student(3,18,"刘备"));
list.add(new Student(4,32,"袁绍"));
list.add(new Student(5,36,"赵云"));
list.add(new Student(6,16,"曹操"));
System.out.println("排序前:");
for (Student student : list) {
System.out.println(student.toString());
}
//使用默认排序
Collections.sort(list);
System.out.println("默认排序后:");
for (Student student : list) {
System.out.println(student.toString());
}
}
输出:
排序前:
Student{id=1, age=25, name='关羽'}
Student{id=2, age=21, name='张飞'}
Student{id=3, age=18, name='刘备'}
Student{id=4, age=32, name='袁绍'}
Student{id=5, age=36, name='赵云'}
Student{id=6, age=16, name='曹操'}
默认排序后:
Student{id=6, age=16, name='曹操'}
Student{id=3, age=18, name='刘备'}
Student{id=2, age=21, name='张飞'}
Student{id=1, age=25, name='关羽'}
Student{id=4, age=32, name='袁绍'}
Student{id=5, age=36, name='赵云'}
比较器的使用
这个时候需求又来了,默认是用 age 排序,但是有的时候需要用 id 来排序怎么办? 这个时候比较器 :Comparator 就排上用场了
Comparator 的使用有两种方式:
- Collections.sort(list,Comparator<T>);
- list.sort(Comparator<T>);
其实主要是看 Comparator 接口的实现,重写里面的 compare 方法。代码如下:
//自定义排序1
Collections.sort(list, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.getId() - o2.getId();
}
});
//自定义排序2
list.sort(new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.getId() - o2.getId();
}
});
正序和倒序:
List<Integer> list = new ArrayList<Integer>();
list.add(6);
list.add(8);
list.add(4);
list.add(5);
//正序排(从小到大)
Collections.sort(list);
System.out.println(list.toString());
//倒叙排(从大到小)
Collections.reverse(list);
System.out.println(list.toString());