java8如何对list中的map元素根据一个key值进行排序

public static void main(String[] args) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("name", "ZK");
        map.put("age", 13);

        Map<String, Object> map2 = new HashMap<String, Object>();
        map2.put("name", "ZA");
        map2.put("age", 15);

        Map<String, Object> map3 = new HashMap<String, Object>();
        map3.put("name", "CX");
        map3.put("age", 20);

        Map<String, Object> map4 = new HashMap<String, Object>();
        map4.put("name", "CX");
        map4.put("age", 18);

        List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
        list.add(map);
        list.add(map2);
        list.add(map3);
        list.add(map4);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

如上的代码排序方式为

 List<Map<String, Object>> collect =
  list.stream().sorted(Comparator.comparing(Test::comparingByName)
 .thenComparing(Comparator.comparing(Test::comparingByAge).reversed()))
                                                     .collect(Collectors.toList());
  • 1
  • 2
  • 3
  • 4

其中Test为你的类名.comparingByName和comparingByAge则是两个方法

private static String comparingByName(Map<String, Object> map){
        return (String) map.get("name");
    }

    private static Integer comparingByAge(Map<String, Object> map){
        return (Integer) map.get("age");
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

借助这两个方法,取出map的参数进行对比

posted on 2020-10-26 12:00  小甜瓜安东泥  阅读(2920)  评论(0编辑  收藏  举报