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

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

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