Collectors.groupingBy 如何对 List<Map<String,Object>>集合分组
//网上对groupingBy的使用都是针对类对象的分组例子,如List<Person>、List<Student>这种。
//可是我这里有如下数据,应该怎么弄呢?

List<Map<String,Object>> list = new ArrayList<>();
Map<String,Object> map = new HashMap<>();
map.put("dicId","aaa");
map.put("dicName","钢材");
map.put("dicDes","钢材1号");
list.add(map);

map = new HashMap<>();
map.put("dicId","bbb");
map.put("dicName","钢筋");
map.put("dicDes","钢筋1号");
list.add(map);
map = new HashMap<>();
map.put("dicId","111");
map.put("dicName","钢筋");
map.put("dicDes","钢筋2号");
list.add(map);

map = new HashMap<>();
map.put("dicId","ccc");
map.put("dicName","河沙");
map.put("dicDes","河沙1号");
list.add(map);

//比如以dicId分组成为Map<String, List<Map<String,Object>>>

2个回答

public void aaa(){
        List<Map<String,Object>> list = new ArrayList<>();
        Map<String,Object> map = new HashMap<>();
        map.put("dicId","aaa");
        map.put("dicName","钢材");
        map.put("dicDes","钢材1号");
        list.add(map);

        map = new HashMap<>();
        map.put("dicId","bbb");
        map.put("dicName","钢筋");
        map.put("dicDes","钢筋1号");
        list.add(map);
        map = new HashMap<>();
        map.put("dicId","111");
        map.put("dicName","钢筋");
        map.put("dicDes","钢筋2号");
        list.add(map);

        map = new HashMap<>();
        map.put("dicId","ccc");
        map.put("dicName","河沙");
        map.put("dicDes","河沙1号");
        list.add(map);
        Map<String, List<Map<String, Object>>> collect = list.stream().collect(Collectors.groupingBy(this::customKey));
    }

    private  String customKey(Map<String,Object> map){
        return map.get("dicId").toString();
    }
xsb_20171227
今天是星期五 谢谢
2 个月之前 回复
public static void main(String[] args) {
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        map.put("dicId", "aaa");
        map.put("dicName", "钢材");
        map.put("dicDes", "钢材1号");
        list.add(map);

        map = new HashMap<>();
        map.put("dicId", "bbb");
        map.put("dicName", "钢筋");
        map.put("dicDes", "钢筋1号");
        list.add(map);
        map = new HashMap<>();
        map.put("dicId", "111");
        map.put("dicName", "钢筋");
        map.put("dicDes", "钢筋2号");
        list.add(map);

        map = new HashMap<>();
        map.put("dicId", "bbb");
        map.put("dicName", "河沙");
        map.put("dicDes", "河沙1号");
        list.add(map);

        //比如以dicId分组成为Map<String, List<Map<String,Object>>>
        Map<String, List<Map<String, Object>>> glist = list.stream().collect(Collectors.groupingBy(e -> e.get("dicId").toString()));

    }
xsb_20171227
今天是星期五 谢谢
2 个月之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问