Collection提供了排序方法sort(),但对于List<Map> 需要根据Map中某一个或某几个Key进行排序,就需要重写sort()方法来实现了;
实现方式如下:
public static void main(String[] args) { List<Map<String, String>> list = new ArrayList<Map<String, String>>(); Map<String, String> map1 = new HashMap<String, String>(); map1.put("id", "1"); map1.put("name", "zhangsan"); Map<String, String> map2 = new HashMap<String, String>(); map2.put("id", "3"); map2.put("name", "zhangsan2"); Map<String, String> map3 = new HashMap<String, String>(); map3.put("id", "4"); map3.put("name", "wangwu2"); Map<String, String> map4 = new HashMap<String, String>(); map4.put("id", "2"); map4.put("name", "zhaoliu"); Map<String, String> map5 = new HashMap<String, String>(); map5.put("id", "4"); map5.put("name", "wangwu1"); list.add(map1); list.add(map3); list.add(map2); list.add(map4); list.add(map5); //排序前 System.out.println("---------------排序前------------------"); for (Map<String, String> map : list) { System.out.println(map); } //先根据ID在根据NAME进行排序 Collections.sort(list, new Comparator<Map<String, String>>() { public int compare(Map<String, String> o1, Map<String, String> o2) { String sort1=o1.get("id")+o1.get("name");//从list中拿出来第一个的id和name拼接到一起 String sort2=o2.get("id")+(String) o2.get("name");//从list中拿出来第二个的id和name拼接到一起 return sort1.compareTo(sort2);//利用String类的compareTo方法 } }); //排序后 System.out.println("---------------排序后------------------"); for (Map<String, String> map : list) { System.out.println(map); } }
结果如下:
---------------排序前------------------ {id=1, name=zhangsan} {id=4, name=wangwu2} {id=3, name=zhangsan2} {id=2, name=zhaoliu} {id=4, name=wangwu1} ---------------排序后------------------ {id=1, name=zhangsan} {id=2, name=zhaoliu} {id=3, name=zhangsan2} {id=4, name=wangwu1} {id=4, name=wangwu2}
上述代码是先根据ID再根据NAME进行排序的,使用MAP中的一个key进行排序只需要获取一个key进行排序即可:
Collections.sort(list, new Comparator<Map<String, String>>() { public int compare(Map<String, String> o1, Map<String, String> o2) { String sort1=o1.get("id");//从list中拿出来第一个的id和name拼接到一起 String sort2=o2.get("id");//从list中拿出来第二个的id和name拼接到一起 return sort1.compareTo(sort2);//利用String类的compareTo方法 } });
List泛型为javaBean同理;
原文地址:https://www.cnblogs.com/ljch/p/12157282.html
时间: 2024-10-03 19:34:14