解决 java循环中使用 Map时 在put值时value值被覆盖的问题

 

其实很简单,只需要把容器换成list

然后在循环中,每次循环末尾map = new HashMap() 或者直接在循环中一开始就实例化hashmap(Map map = new HashMap();),这样就不会造成map覆盖了。

注:Map map = new HashMap(); 如果是在循环场景下使用,则必须在循环中以局部实例化的方式出现,见示例2 fetchAssetsList 方法。

 

复制代码
copy
    @RequestMapping("controller/json/AssetsController/getAssetsInfosysAndType")
    @ResponseBody
    public Msg getAssetsInfosysAndType() {
        List list = new ArrayList();
        List<AssetsInfosys> assetsInfoSysServiceAll = assetsInfoSysService.getAll();
        List<AssetsStructureLowerMenu> lowerMenuServiceAll = assetsStructureLowerMenuService.getAll();
        for (AssetsInfosys ai :
                assetsInfoSysServiceAll) {
            for (AssetsStructureLowerMenu lmsa :
                    lowerMenuServiceAll) {
                if (ai.getName().equals(lmsa.getSuperiormenu())) {
                    Map map = new HashMap();
                    map.put("assetsInfoSys", ai);
                    map.put("msgAssetsType", lmsa);
                    list.add(map);
                }
            }
        }
        return Msg.success().add("AllMsgAssetsInfosysAndType", list);
    }
复制代码

 

示例2:(fetchAssetsList方法)

 

posted @   由良大小姐  阅读(9103)  评论(0编辑  收藏  举报
编辑推荐:
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
· .NET Core内存结构体系(Windows环境)底层原理浅谈
· C# 深度学习:对抗生成网络(GAN)训练头像生成模型
· .NET 适配 HarmonyOS 进展
点击右上角即可分享
微信分享提示
💬
评论
📌
收藏
💗
关注
👍
推荐
🚀
回顶
收起