Comparator接口实现排序

Interface Comparator<T>

单一条件排序:

List<Student> stus = new ArrayList<Student>(){
{
}
};
//对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());
}
});
// 输出结果
...

List<Student> stus = new ArrayList<Student>(){
{
}
};
//对users按年龄进行排序
Collections.sort(stus, (s1,s2)->(s1.getAge()-s2.getAge()));

lambda表达式是JDK8新特性之一, 允许你通过表达式来代替功能接口; 细节请自行百度… 我也是刚接触, 啊哈哈, 不熟悉,谅解谅解

多条件排序:

List<Student> stus = new ArrayList<Student>(){
{
}
};
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());
}

自定义条件排序

String[] order = {"语文","数学","英语","物理","化学","生物","政治","历史","地理","总分"};
final List<String> defiderOrder = Arrays.asList(order);
List<String> list = new ArrayList<String>(){
{
}
};
Collections.sort(list,new Comparator<String>() {

@Override
public int compare(String o1, String o2) {
int io1 = defiderOrder.indexOf(o1);
int io2 = defiderOrder.indexOf(o2);
return io1-io2;
}
});

for(String s:list){
System.out.print(s+"   ");
}

Collections.sort(list, (o1, o2)->(defiderOrder.indexOf(o1)-defiderOrder.indexOf(o2)));