对任意类型集合对象进行整体排序,排序时将此接口的实现传递给Collections.sort方法或者Arrays.sort方法排序. 实现int compare(T o1, T o2);方法,返回正数,零,负数各代表大于,等于,小于。
单一条件排序:
举例:
List<Student> stus = new ArrayList<>();
Student stu1 = new Student();
Student stu2 = new Student();
Student stu3 = new Student();
stu1.setName("张三");
stu1.setAge(30);
stu2.setName("李四");
stu2.setAge(20);
stu3.setName("王五");
stu3.setAge(60);
stus.add(stu1);
stus.add(stu2);
stus.add(stu3);
//对users按年龄进行排序
Collections.sort(stus, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
// 升序
//return o1.getAge()-o2.getAge();
return o1.getAge().compareTo(o2.getAge());
// 降序
// return o2.getAge()-o1.getAge();
// return o2.getAge().compareTo(o1.getAge());
}
});
// 输出结果
...
123456789101112131415161718192021222324252627282930313233
多条件排序:
举例:
List<Student> stus = new ArrayList<>();
Student stu1 = new Student();
Student stu2 = new Student();
Student stu3 = new Student();
Student stu4 = new Student();
Student stu5 = new Student();
Student stu6 = new Student();
stu1.setAge(30);
stu2.setAge(20);
stu3.setAge(40);
stu4.setAge(30);
stu5.setAge(40);
stu6.setAge(20);
stu1.setNum(1);
stu2.setNum(2);
stu3.setNum(3);
stu4.setNum(4);
stu5.setNum(5);
stu6.setNum(6);
stu1.setName("张三");
stu2.setName("李四");
stu3.setName("王五");
stu4.setName("赵六");
stu5.setName("陈七");
stu6.setName("周八");
stus.add(stu1);
stus.add(stu2);
stus.add(stu3);
stus.add(stu4);
stus.add(stu5);
stus.add(stu6);
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());
}
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
输出结果:
自定义条件排序
String[] order = {"语文","数学","英语","物理","化学","生物","政治","历史","地理","总分"};
final List<String> defiderOrder = Arrays.asList(order);
List<String> list = new ArrayList<>();
list.add("总分");
list.add("英语");
list.add("政治");
list.add("总分");
list.add("数学");
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+" ");
}
123456789101112131415161718192021
输出结果:
CSDN 原文:https://blog.csdn.net/lx_nhs/article/details/78871295?
本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。