方法:实现Comparator接口并重写它的compare()方法,在方法内部制定排序规则。
我们有如下学生类,在不改变学生类源码的情况下,按照某种规则,对集合中存储的学生对象进行排序。
public class Student {
private String id;
private String name;
private int chinese;
private int math;
private int english;
public Student() {
super();
}
public Student(String id, String name, int chinese, int math, int english) {
super();
this.id = id;
this.name = name;
this.chinese = chinese;
this.math = math;
this.english = english;
}
.....省略setter和getter方法
}
}
1.利用TreeSet在添加元素前指定排序规则(这里是按语文成绩进行排序)
public class TreeSetSortTest {
public static void main(String[] args) {
TreeSet<Student> ts = new TreeSet<Student>( new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.getChinese()-o2.getChinese();
}
});
ts.add(new Student("001", "张三", 90, 88, 76));
ts.add(new Student("002", "李四", 98, 78, 90));
ts.add(new Student("003", "jack", 78, 68, 55));
for (Student student : ts) {
System.out.println(student);
}
}
}
打印结果:
Student [id=003, name=jack, chinese=78, math=68, english=55]
Student [id=001, name=张三, chinese=90, math=88, english=76]
Student [id=002, name=李四, chinese=98, math=78, english=90]
2.利用ArrayList集合存储学生对象,使用工具类Collections.sort ( List<T> list,Comparator<? super T> c)操作集合,对集合进行排序
public class ArrayListSortTest {
public static void main(String[] args) {
ArrayList<Student> list = new ArrayList<Student>();
list.add(new Student("001", "张三", 90, 88, 76));
list.add(new Student("002", "李四", 98, 78, 90));
list.add(new Student("003", "jack", 78, 68, 55));
Collections.sort(list, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.getMath()-o2.getMath();
}
});
for (Student student : list) {
System.out.println(student);
}
}
}
打印结果:
Student [id=003, name=jack, chinese=78, math=68, english=55]
Student [id=002, name=李四, chinese=98, math=78, english=90]
Student [id=001, name=张三, chinese=90, math=88, english=76]