Collections对List集合中的数据进行排序
1.对于普通对象
public static void main(String[] args) {
List<Integer> nums = new ArrayList<Integer>();
nums.add(3);
nums.add(5);
nums.add(1);
nums.add(0);
System.out.println(nums);
Collections.sort(nums);
System.out.println(nums);
}
输出结果:
[3, 5, 1, 0]
[0, 1, 3, 5]
2.对于复杂对象
public class User implements Comparable<User>{
private int score;
private int age;
public User(int score, int age){
super();
this.score = score;
this.age = age;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public int compareTo(User o) {
int i = this.getAge() - o.getAge();//先按照年龄排序
if(i == 0){
return this.score - o.getScore();//如果年龄相等了再用分数进行排序
}
return i;
}
}
public static void main(String[] args) {
List<User> users = new ArrayList<User>();
users.add(new User(78, 26));
users.add(new User(67, 23));
users.add(new User(34, 56));
users.add(new User(55, 23));
Collections.sort(users);
for(User user : users){
System.out.println(user.getScore() + "," + user.getAge());
}
}
输出结果:
55,23
67,23
78,26
34,56
3.对于集合类型的对象
需要提供比较器Collections.sort(list,comparator),当然上面的例子也可以提供比较器
public abstract class ListMapSortComparator implements Comparator<Map<String, Object>> {
private String key;
private String order;
public ListMapSortComparator(String key,String order) {
this.key = key;
this.order = order;
}
/*
* (non-Javadoc)
*
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
@Override
public int compare(Map<String, Object> o1, Map<String, Object> o2){
if (order.equals("asc")) {
if (o1.get(key) instanceof Integer) {
return Integer.valueOf(o1.get(key).toString())
- Integer.valueOf(o2.get(key).toString());
} else {
return o1.get(key).toString().compareTo(o2.get(key).toString());
}
} else {
if (o2.get(key) instanceof Integer) {
return Integer.valueOf(o2.get(key).toString())
- Integer.valueOf(o1.get(key).toString());
} else {
return o2.get(key).toString().compareTo(o1.get(key).toString());
}
}
}
}
调用代码
public class testListMapSort {
@Test
public void test() {
String str1 = "cccc";
String str2 = "aaaa";
String str3 = "bbbb";
String person1 ="陈维";
String person2 = "吴浩然";
String person3 = "赵子露";
Map<String, Object> map1 = new HashMap<String, Object>();
Map<String, Object> map2 = new HashMap<String, Object>();
Map<String, Object> map3 = new HashMap<String, Object>();
map1.put(str1, person1);
map2.put(str2, person2);
map3.put(str3, person3);
List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
list.add(map1);
list.add(map2);
list.add(map3);
System.out.println(list);
Collections.sort(list,new ListMapSortComparator("","desc") {
});
System.out.println(list);
}
}
结果:
[{cccc=陈维}, {aaaa=吴浩然}, {bbbb=赵子露}]