weixin_45056333
weixin_45056333
采纳率50%
2019-10-20 21:04

java的List集合里面放了Map,List<Map<String,Object>>,如何判定人名相同,就组合成一个对象?

已采纳

之前的数据样例:
[
{
"name": "张三",
"公司": "腾讯"
},
{
"name": "李四",
"公司": "阿里"
},
{
"name": "王五",
"公司": "百度"
},
{
"name": "张三",
"地址": "四川"
},
{
"name": "李四",
"地址": "湖南"
},
{
"name": "王五",
"地址": "广东"
}
]

我需要的数据:
[
{
"name": "张三",
"公司": "腾讯",
"地址": "四川"
},
{
"name": "李四",
"公司": "阿里",
"地址": "湖南"
},
{
"name": "王五",
"公司": "百度",
"地址": "广东"
}
]

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • weixin_41763995 _鹿慕溪水 2年前
    public static void main(String[] args) {
    
            List<Map<String, Object>> list = new ArrayList<>();
            Map<String, Object> objectMap = new HashMap<>();
            objectMap.put("name","张三");
            objectMap.put("公司","腾讯");
            Map<String, Object> objectMap1 = new HashMap<>();
            objectMap1.put("name","李四");
            objectMap1.put("公司","阿里");
            Map<String, Object> objectMap2 = new HashMap<>();
            objectMap2.put("name","王五");
            objectMap2.put("公司","百度");
            Map<String, Object> objectMap3 = new HashMap<>();
            objectMap3.put("name","王五");
            objectMap3.put("地址","北京");
            list.add(objectMap);
            list.add(objectMap1);
            list.add(objectMap2);
            list.add(objectMap3);
            Map<String, Map<String,Object>> map = new HashMap<>();
            list.forEach((s)->{
                if(map.containsKey(s.get("name"))){
                    Map<String, Object> map1 = map.get(s.get("name"));
                    map1.putAll(s);
                }else{
                    Map<String, Object> newMap = new HashMap<>();
                    newMap.putAll(s);
                    map.put(s.get("name").toString(),newMap);
                }
            });
            map.forEach((k,v)->{
                System.out.println(k);
                v.forEach((e,a)->{
                    System.out.println(e+":"+a);
                });
    
            });
        }
    

    参考博文:https://blog.csdn.net/weixin_41763995/article/details/80223244

    点赞 1 评论 复制链接分享
  • wojiushiwo945you 毕小宝 2年前

    思路,用 Map 的方式解决,遍历列表,以 name 为 key ,参考代码如下:

    Map<String,Map<String,String>> nameAndElements = new HashMap<String,,Map<String,String>>();//以 name 为 key 存储合并后的数据
    for(int i=0;i<data.size();i++){
      Map<String,String> temp = data.getIndexAt(i);
        String name = temp.get("name");
        if(nameAndElements.contains(name)){
          //存在,合并
            Map<String,String> currentInfo = nameAndElements.get(name);
            currentInfo.put("company",temp.get("company");
            currentInfo.put("address",temp.get("address");
        }else{
          // 新记录
            nameAndElements.put(name,temp);
        }
    }
    
    点赞 1 评论 复制链接分享