Bootstrap

java的stream流的list根据某字段分组

  @Test
    public void  test1(){
        List<Map<String,Object>> list2 = new ArrayList<>();
        Map<String,Object> map1 = new HashMap<>();
        map1.put("region", "410185");
        map1.put("positionText", "服务员");
        map1.put("urgent", "1");
        list2.add(map1);
        Map<String,Object> map2 = new HashMap<>();
        map2.put("region", "410100");
        map2.put("positionText", "按摩师");
        map2.put("urgent", "2");
        list2.add(map2);
        Map<String,Object> map3 = new HashMap<>();
        map3.put("region", "410100");
        map3.put("positionText", "服务员");
        map3.put("urgent", "2");
        list2.add(map3);
        Map<String,Object> map4 = new HashMap<>();
        map4.put("region", "410155");
        map4.put("positionText", "会计");
        map4.put("urgent", "1");
        list2.add(map4);
        List<Map<String, Object>> groupList = list2.stream().collect(Collectors.groupingBy(d -> d.get("region"))).entrySet()
                .stream().map(d -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("recruitList", d.getValue());
                    map.put("region", d.getKey());
                    return map;
                }).collect(Collectors.toList());

        System.out.println(JSONObject.toJSON(groupList));
    }

最后输出的结果在这里插入图片描述

;