使用HashSet<String>将map集合去重

    在前面的博客中讲过用map做小实体,接收数据。现在业务要求是:对实体集合去重;

一、总体思想:

使用HashSet<String>将map集合去重。

1、取出List<Entity> oldList中的userId,用HashSet<String>removalManagerIdList集合接收,自动去重;(可借鉴:利用HashSet对数组去重

2、新建List<Entity> newList,遍历List<Entity> oldList 和 HashSet<String> removalManagerIdList,从List<Entity> oldList取出与HashSet<String> removalManagerIdList中对应的值,将新值保存到List<Entity> newList;

二、细节:

1、外循环:HashSet<String> removalManagerIdList,内循环:List<Entity> oldList;

2、问题:内循环中有重复值,一个外循环的userId每遍历一次内循环时,如果userId相同就会新建一个实体,这样仍然达不到去重的效果;解决方法:外循环找到userId相同的内循环实体时,给新实体赋值后,停止遍历内循环;


三、代码实现:

public void parseMap(List<AssetDeptManagerConfig> managerLists, AssetDeptManagerConfigVo 

assetDeptManagerConfigVo,
        List<HashMap<String, String>> mapList, String ManagerBizType) {

        // 使用HashSet<String>将map集合去重;
        HashSet<String> removalManagerIdList = new HashSet<>();      // 接收被去重的集合的userId
        for (HashMap<String, String> map : mapList) {
                removalManagerIdList.add(map.get("userId"));
        }
        // 遍历HashSet<String>,对每个managerId赋值(此时的removalManagerIdList中没有重复的userId)
        for (String removalManagerId : removalManagerIdList) {
                boolean equalTag = false;     //  标识是否找到对应的userId
                for (HashMap<String, String> map : mapList) {
                        if (map.get("userId").equals(removalManagerId)) {
                                AssetDeptManagerConfig manager = new AssetDeptManagerConfig();
                                manager.setManagerId(map.get("userId"));
                                manager.setManagerName(map.get("userName"));
                                manager.setDeptId(assetDeptManagerConfigVo.getDeptId());
                                manager.setDeptName(assetDeptManagerConfigVo.getDeptName());
                                manager.setManagerBizType(ManagerBizType);
                                manager.setManagerType(assetDeptManagerConfigVo.getManagerType());
                                manager.setOrgId(this.userService.getUser().getOrgId());
                                managerLists.add(manager);
                                equalTag = true;  // 找到userId,退出循环,进入下一个外循环;
                                break;
                        }
                }

        }
        }

四、其他方法:

为Entity重写equal方法:

set实体泛型对象去重(重写实体hashCode、equal方法)

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 21
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 21
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小王师傅66

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值