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

来源:互联网 发布:逆战弹道优化 编辑:程序博客网 时间:2024/05/17 06:21

    在前面的博客中讲过用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方法)

原创粉丝点击