# Comparator接口实现排序

Interface Comparator<T>


## 单一条件排序:

		List<Student> stus = new ArrayList<Student>(){
{
}
};
// 1.对学生集合按年龄进行排序
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());
}
});

// 2.对学生集合按姓名首字母排序
Comparator comparator = Collator.getInstance(Locale.CHINA);
Collections.sort(stus, new Comparator<Student>() {

@Override
public int compare(Student s1, Student s2) {
return comparator.compare(s1.getName(), s2.getName());
}

});

// 输出结果
...



		List<Student> stus = new ArrayList<Student>(){
{
}
};
//对学生集合按年龄进行排序
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> definedOrder = 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 = 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)));


03-16

02-15 14万+
05-16 8379
12-26 5万+
06-03 7022
07-01 1万+
07-08 1万+
08-05 7162
06-28 1238
04-21 3659
09-01 6048
07-11 1337
03-06 5503