List>集合根据map里面的一个字段排序

通过实现Comparator接口实现排序,

列子:一个Map<String,Object> 中建 key有name,age 字段,name为名字,age为年龄,现在根据年龄排序代码如下:

@Test
public void testMapOrder() {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
Map<String, Object> map1 = new HashMap<String, Object>();
map1.put("name", "张三");//名字
map1.put("age", 22);    //年龄
list.add(map1);
Map<String, Object> map3 = new HashMap<String, Object>();
map3.put("name", "王五");
map3.put("age", 38);
list.add(map3);
Map<String, Object> map5 = new HashMap<String, Object>();
map5.put("name", "谢七");
map5.put("age", 20);
list.add(map5);
Map<String, Object> map6 = new HashMap<String, Object>();
map6.put("name", "张三");
map6.put("age", 22);
list.add(map6);
//匿名实现Comparator接口进行排序
Collections.sort(list, new Comparator<Map<String,Object>>() {
@Override
public int compare(Map<String, Object> o1, Map<String, Object> o2) {
//进行判断
return ((Integer)o1.get("age")).compareTo((Integer)o2.get("age"));
}
});
for(Map<String,Object> m:list){
System.out.println("Map[name="+m.get("name")+"age="+m.get("age")+"]");
}
}

结果:控制台打印

Map[name=谢七age=20]
Map[name=张三age=22]
Map[name=张三age=22]
Map[name=李四age=24]
Map[name=赵六age=36]
Map[name=王五age=38]

 

你可能感兴趣的:(java,comparator,List>排序)