源码请见共享目录CSDN/JavaSE基础/2. ListSort.zip
一、目标
- 对整型的List集合排序;
- 对装有对象的List集合的某列排序;
- 对装有对象的List集合的综合排序;
二、实践
2.1 对整型的List排序
public class SortIntegerList {
public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {
//准备List中的数据
List<Integer> list = new ArrayList<Integer>();
for(int i=0;i<12;i++){
Integer random = (int) (Math.random()*100);
list.add(random);
}
//打印列表
System.out.print("排序前:");
IntegerPrinter.print(list);
//排序
Collections.sort(list);
//打印列表
System.out.print("排序前:");
IntegerPrinter.print(list);
//list集合反序
Collections.reverse(list);
//打印列表
System.out.print("排序前:");
IntegerPrinter.print(list);
}
}
- Collections.sort(list)可以对Integer、float、String等类型的list集合进行排序,默认是升序排序;
- Collections.reverse(list)可以对List进行反序;
- 不能使用Collections.sort(list)对自定义对象类型进行排序,没用!
2.2 对对象的List排序
public class SortObjectList {
public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {
//准备数据
List<Foo> list = new ArrayList<Foo>();
Foo f = new Foo("zjs", "zjs1");
list.add(f);
f = new Foo("zeg", "zeg1");
list.add(f);
f = new Foo("atx", "atx1");
list.add(f);
f = new Foo("xa", "xa1");
list.add(f);
f = new Foo("dx", "dx1");
list.add(f);
//打印序列
System.out.println("################排序前####################");
FooPrinter.print(list);
//降序排序
Collections.sort(list,new Comparator<Foo>() {
@Override
public int compare(Foo a, Foo b) {
//根据name字段排序
String one = a.getName();
String two = b.getName();
if(one.compareTo(two)>0)return 1;
else return -1;
}
});
//打印序列
System.out.println("################排序后####################");
FooPrinter.print(list);
}
}
- 使用Collections.sort(List,Comparator)对自定义对象的List排序;
- 在这个Comparator比较器中,需要自己比较第1个对象a和第2个对象b,根据返回正、负值控制其是升序还是逆序;
2.3 对对象的List综合排序
public class MulSortObjectList {
public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {
List<Foo> list = new ArrayList<Foo>();
Foo f = new Foo("zjs", "zjs2");
list.add(f);
f = new Foo("zjs", "zjs1");
list.add(f);
f = new Foo("atx", "atx1");
list.add(f);
f = new Foo("xa", "xa1");
list.add(f);
f = new Foo("at", "atxs2");
list.add(f);
//打印序列
System.out.println("################排序前####################");
FooPrinter.print(list);
Collections.sort(list,new Comparator<Foo>() {
@Override
public int compare(Foo a, Foo b) {
String one = a.getName();
String two = b.getName();
int val = one.compareTo(two);
if(val>0)return 1;
else if(val<0)return -1;
else{
String one2 = a.getHelo();
String two2 = b.getHelo();
int val2 = one2.compareTo(two2);
if(val2>0)return 1;
else return -1;
}
}
});
//打印序列
System.out.println("################排序后####################");
FooPrinter.print(list);
}
}
- 结合2.2中的排序,于是在比较第一个元素的name属性字段的同时,在当第一个属性相等时,比较第2个属性,综合两次比较来控制顺序;
三、分析原理
理解有限,暂不做描述!
四、总结
- 普通类型(Integer、float等)的List集合的排序使用Collections.sort(List)即可实现;
- 对特殊的List集合排序,使用Collections.sort(List,Comparator)排序,需要自定义比较器Comparator控制排序是升序还是降序;
- 使用Collections.reverse(list)可以对List集合进行反序;