有一个列表:List list
现在使用 Collections 对其进行排序:
...
List<Integer> list=new ArrayList<>();
list.add(13);
list.add(34);
list.add(42);
//排序
Collections.sort(list,new Comparator<Integer>(){
public int compare(Integer i1,Integer i2){
return i1.compareTo(i2); //升序
//return i2.compareTo(i1); //降序
}
});
return list;
如果列表里是个Map:List<Map<String,Object>> list
也可以使用 Collections 对其进行排序
...
List<Map<String,Object>> list=new ArrayList<>();
Map<String,Object> map1=new HashMap<>();
map1.put("totol",52831);
map1.put("name","name1");
map1.put("age","age1");
Map<String,Object> map2=new HashMap<>();
map2.put("total",72394);
map2.put("name","name2");
map2.put("age","age2");
Map<String,Object> map3=new HashMap<>();
map3.put("total",34356);
map3.put("name","name3");
map3.put("age","age3");
list.add(map1);
list.add(map2);
list.add(map3);
//按照map中total字段排序
Collections.sort(list,new Comparator<Map<String,Object>>(){
public int compare(Map<String,Object> o1 ,Map<String,Object> o2){
Integer num1=(Integer)o1.get("total");
Integer num2=(Integer)o2.get("total");
return num2.compareTo(num1); //降序
//return num1.compareTo(num2); //升序
}
});
return list;