java对list中map集合中某个字段排序

  • Post author:
  • Post category:java




java对list中map集合中某个字段排序


适用于字符串排序,数字对比不可用,以下示例,当把sort的值改为74,66,142时排序不对看示例2


示例1

List<Map<String, Object>> content = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        map.put("sort", 2);
        map.put("name", "qwe");
        content.add(map);
        Map<String, Object> map1 = new HashMap<>();
        map1.put("sort", 1);
        map1.put("name", "rty");
        content.add(map1);
        Map<String, Object> map2 = new HashMap<>();
        map2.put("sort", 3);
        map2.put("name", "uio");
        content.add(map2);
        System.out.println(content);
        //结果
        //[{name=qwe, sort=2}, {name=rty, sort=1}, {name=uio, sort=3}]
        Collections.sort(content, new Comparator<Map<String, Object>>() {
            @Override
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
	            if (o1.get("sort") == null && o2.get("sort") == null){
                   return 0;
                }else if (o1.get("sort") == null){
                    return 1;
                }else if (o2.get("sort") == null){
                    return -1;
                }else{
                    return o1.get("sort").toString().compareTo(o2.get("sort").toString());
                }
            }
        });
        System.out.println(content);
        //[{name=rty, sort=1}, {name=qwe, sort=2}, {name=uio, sort=3}]

也可以写的更简洁点使用java8提供的stream

//1 普通版
content.sort((o1, o2) -> o1.get("sort").toString().compareTo(o2.get("sort").toString()));
//2最精简
 content.sort(Comparator.comparing(o -> o.get("sort").toString()));


示例2

List<Map<String, Object>> content = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        map.put("sort", 74);
        map.put("name", "qwe");
        content.add(map);
        Map<String, Object> map1 = new HashMap<>();
        map1.put("sort", 62);
        map1.put("name", "rty");
        content.add(map1);
        Map<String, Object> map2 = new HashMap<>();
        map2.put("sort", 142);
        map2.put("name", "uio");
        content.add(map2);
        System.out.println(content);
         //[{name=qwe, sort=74}, {name=rty, sort=62}, {name=uio, sort=142}]
        //结果
        Collections.sort(content, new Comparator<Map<String, Object>>() {
            @Override
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                if (o1.get("sort") == null && o2.get("sort") == null){
                    return 0;
                }else if (o1.get("sort") == null){
                    return 1;
                }else if (o2.get("sort") == null){
                    return -1;
                }else{
                    return o1.get("sort").toString().compareTo(o2.get("sort").toString());
                }
            }
        });
        System.out.println(content);
        //[{name=uio, sort=142}, {name=rty, sort=62}, {name=qwe, sort=74}]

    }