1.對List集合裡儲存的map其中一個key的值,進行排序
例:
List<Map<String, Object>> list= new ArrayList();
注:list裡面存在 name屬性
//排序 倒序 對key為name 的值進行排序
if (!getList.isEmpty()) {
Collections.sort(list, new Comparator<Map<String, Object>>() {
@Override
public int compare(Map<String, Object> o1, Map<String, Object> o2) {
Integer o1Value = Integer.valueOf(o1.get("count").toString());
Integer o2Value = Integer.valueOf(o2.get("count").toString());
return o2Value.compareTo(o1Value);
}
});
}
//正序就把值反過來 : return o1Value.compareTo(o2Value);
2.還可以以流的形式進行排序,多字段進行排序
private static int comparator(Object o, Object o1) {
Map map1 = Convert.convert(Map.class, o);
Map map2 = Convert.convert(Map.class, o1);
if (map1 == null && map2 == null)
return 0;
if (map1 == null || map2 == null) {
throw new NullPointerException();
}
String name1 = (String) map1.get("name");
String name2 = (String) map2.get("name");
int c = name1.compareTo(name2);
if (c != 0)
return c;
int age1 = (int) map1.get("age");
int age2 = (int) map2.get("age");
return age2 - age1;
}
public static void main(String[] args) {
Map map = new HashMap();
map.put("name", "張三");
map.put("age", 22);
Map map2 = new HashMap();
map2.put("name", "李四");
map2.put("age", 25);
Map map3 = new HashMap();
map3.put("name", "王五");
map3.put("age", 26);
Map map4 = new HashMap();
map4.put("name", "錢七");
map4.put("age", 28);
List list = new ArrayList();
list.add(map);
list.add(map2);
list.add(map3);
list.add(map4);
Stream stream = list.stream();
List<Map>list2=(List<Map>)stream.sorted(Demo::comparator).collect(Collectors.toList());
for (Map m : list2) {
System.out.println(m.get("name") + " " + m.get("age"));
}
}