List排序
1、使用Collections的sort(List list)方法对List集合进行从小到大排序
/*** 使用Collections的sort(List list)方法对List集合进行从小到大排序*/@Testpublic voidlistDefaultSort() {
List list = new ArrayList();
list.add(1);
list.add(3);
list.add(2);
System.out.println(list);
System.out.println("------------------");
Collections.sort(list);//按从小到大排序,只能对基本数据类型的包装对象
System.out.println(list);
}
View Code
执行结果:
[1, 3, 2]------------------[1, 2, 3]
View Code
2、使用Collections的sort(List list, Comparator super T> c)方法对List集合进行自定义排序
/*** 使用Collections的sort(List list, Comparator super T> c)方法对List集合进行自定义排序*/@Testpublic voidlistCustomSort() {
List list = new ArrayList();
Person p1= new Person("1", "p1" , 12);
Person p2= new Person("2", "p2" , 9);
Person p3= new Person("3", "p3" , 13);
Person p4= new Person("4", "p4" , 9);
list.add(p1);
list.add(p2);
list.add(p3);
list.add(p4);
System.out.println(list);
System.out.println("------------------");
Collections.sort(list,new Comparator() {//按年龄从大到小排序
@Overridepublic intcompare(Person p1, Person p2) {return p1.getAge() == p2.getAge() ? 0 : (p1.getAge() < p2.getAge() ? 1 : -1);
}
});
System.out.println(list);
}
View Code
classPerson {privateString id;privateString name;private intage;public Person(String id, String name, intage) {super();this.id =id;this.name =name;this.age =age;
}publicString getId() {returnid;
}public voidsetId(String id) {this.id =id;
}publicString getName() {returnname;
}public voidsetName(String name) {this.name =name;
}public intgetAge() {returnage;
}public void setAge(intage) {this.age =age;
}
@OverridepublicString toString() {return "\n Person [id=" + id + ", name=" + name + ", age=" + age