如何比较两个Map列表返回缺失元素?合并列表并去重的方法
解决List<Map<String,String>>的元素对比与合并去重问题
一、找出两个列表中彼此缺失的元素
这里默认以Map的所有键值对完全匹配作为元素重复的判断标准(依赖HashMap原生的equals()方法),如果业务中只需基于特定字段(如id)判断,可参考下方说明修改逻辑。
1. 提取customerDetails独有的元素
List<Map<String, String>> onlyInCustomer = customerDetails.stream() .filter(custMap -> accountDetails.stream().noneMatch(accMap -> accMap.equals(custMap))) .collect(Collectors.toList()); // 结果:包含Andy对应的Map元素
2. 提取accountDetails独有的元素
List<Map<String, String>> onlyInAccount = accountDetails.stream() .filter(accMap -> customerDetails.stream().noneMatch(custMap -> custMap.equals(accMap))) .collect(Collectors.toList()); // 结果:空列表(示例中accountDetails的元素都存在于customerDetails)
自定义判断规则示例:如果仅用id字段判断元素唯一性,修改过滤条件即可:
// 仅按id筛选customerDetails独有的元素 List<Map<String, String>> onlyInCustomerById = customerDetails.stream() .filter(custMap -> accountDetails.stream().noneMatch(accMap -> accMap.get("id").equals(custMap.get("id")))) .collect(Collectors.toList());
二、合并两个列表并去重
方式1:Stream拼接+去重
利用Stream的concat和distinct方法,基于Map的全键值对匹配去重:
List<Map<String, String>> mergedList = Stream.concat(customerDetails.stream(), accountDetails.stream()) .distinct() .collect(Collectors.toList()); // 结果:包含Andy、Tom、Mary三条不重复的Map元素
方式2:Set集合去重
Set会自动过滤重复元素,再转回List:
Set<Map<String, String>> tempSet = new HashSet<>(); tempSet.addAll(customerDetails); tempSet.addAll(accountDetails); List<Map<String, String>> mergedList = new ArrayList<>(tempSet);
自定义去重规则示例:基于id字段去重,保留先出现的元素:
List<Map<String, String>> mergedById = Stream.concat(customerDetails.stream(), accountDetails.stream()) .collect(Collectors.toMap( map -> map.get("id"), Function.identity(), (existing, newOne) -> existing // 重复时保留原有元素 )) .values() .stream() .collect(Collectors.toList());
内容的提问来源于stack exchange,提问作者nithinc
相关产品推荐
相关产品推荐

