Interface Comparator<T>
Arrays.sort(T[],Comparator<? super T> c);
Collections.sort(List<T> list,Comparator<? super T> c);
对任意类型集合对象进行整体排序,排序时将此接口的实现传递给Collections.sort方法或者Arrays.sort方法排序.
实现int compare(T o1, T o2);方法,返回正数,零,负数各代表大于,等于,小于。
1、单一条件排序:
List<Student> stus = new ArrayList<Student>(){
{
add(new Student("张三", 30));
add(new Student("李四", 20));
add(new Student("王五", 60));
}
};
//对users按年龄进行排序
Collections.sort(stus, new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
// 升序
//return s1.getAge()-s2.getAge();
return s1.getAge().compareTo(s2.getAge());
// 降序
// return s2.getAge()-s1.getAge();
// return s2.getAge().compareTo(s1.getAge());
}
});
注: 还可以使用lambda表达式简化代码, 前提是JDK8开发环境, 如下:
List<Student> stus = new ArrayList<Student>(){
{
add(new Student("张三", 30));
add(new Student("李四", 20));
add(new Student("王五", 60));
}
};
//对users按年龄进行排序
Collections.sort(stus, (s1,s2)->(s1.getAge()-s2.getAge()));
2、多条件排序:
List<Student> stus = new ArrayList<Student>(){
{
add(new Student("张三", 30, 1));
add(new Student("李四", 20, 2));
add(new Student("王五", 40, 3));
add(new Student("赵六", 30, 4));
add(new Student("陈七", 40, 5));
add(new Student("周八", 20, 6));
}
};
Collections.sort(stus,new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
int flag;
// 首选按年龄升序排序
flag = s1.getAge()-s2.getAge();
if(flag==0){
// 再按学号升序排序
flag = s1.getNum()-s2.getNum();
}
return flag;
}
});
System.out.println("年龄 学号 姓名 ");
for(Student s : stus){
System.out.println(s.getAge()+" "+s.getNum()+" "+s.getName());
}
3、自定义条件排序
String[] order = {"语文", "数学", "英语", "物理", "化学", "生物", "政治", "历史", "地理", "总分"};
final List<String> definedOrder = Arrays.asList(order);
List<String> list = new ArrayList<String>() {
{
add("总分");
add("英语");
add("政治");
add("总分");
add("数学");
}
};
Collections.sort(list, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
int io1 = definedOrder.indexOf(o1);
int io2 = definedOrder.indexOf(o2);
return io1 - io2;
}
});
for (String s : list) {
System.out.print(s + " ");
}
//数学 英语 政治 总分 总分
Collections.sort(list, (o1, o2)->(definedOrder .indexOf(o1)-definedOrder .indexOf(o2)));