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

 List> content = new ArrayList<>();
        Map map = new HashMap<>();
        map.put("sort", 2);
        map.put("name", "qwe");
        content.add(map);
        Map map1 = new HashMap<>();
        map1.put("sort", 1);
        map1.put("name", "rty");
        content.add(map1);
        Map 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>() {
            @Override
            public int compare(Map o1, Map o2) {
                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()));

 

你可能感兴趣的:(java)