如何用Stream实现HashMap匹配校验并生成新Map,不匹配时抛异常
解决方案
核心思路
先校验firstMap的所有键是否都存在于secondMap中,若有缺失直接抛出异常;验证通过后,再安全构建映射关系并为mapRecords赋值,同时优化原嵌套循环逻辑提升执行效率。
具体实现代码
import java.util.*; import java.util.stream.Collectors; public class TestMap { private Long firstId; private Long secondId; public TestMap(Long firstId, Long secondId) { this.firstId = firstId; this.secondId = secondId; } // Getter & Setter public Long getFirstId() { return firstId; } public void setFirstId(Long firstId) { this.firstId = firstId; } public Long getSecondId() { return secondId; } public void setSecondId(Long secondId) { this.secondId = secondId; } public static void main(String[] args) { List<TestMap> mapRecords = new ArrayList<>(); mapRecords.add(new TestMap(1L, null)); mapRecords.add(new TestMap(2L, null)); mapRecords.add(new TestMap(3L, null)); Map<Long, Long> firstMap = new HashMap<>(); firstMap.put(11L, 1L); firstMap.put(22L, 2L); firstMap.put(33L, 3L); Map<Long, Long> secondMap = new HashMap<>(); secondMap.put(11L, 111L); secondMap.put(22L, 222L); // 测试异常逻辑可打开此行:secondMap.put(33L, 333L); // 1. 校验firstMap的键是否全部存在于secondMap Set<Long> missingKeys = firstMap.keySet().stream() .filter(key -> !secondMap.containsKey(key)) .collect(Collectors.toSet()); if (!missingKeys.isEmpty()) { throw new IllegalArgumentException("secondMap中缺失必填键: " + missingKeys); } // 2. 构建最终映射:firstMap的值为键,secondMap对应值为值 Map<Long, Long> finalMap = firstMap.entrySet().stream() .collect(Collectors.toMap( Map.Entry::getValue, entry -> secondMap.get(entry.getKey()) )); // 3. 为mapRecords批量设置secondId(优化原嵌套循环) mapRecords.forEach(record -> record.setSecondId(finalMap.get(record.getFirstId()))); // 测试输出 mapRecords.forEach(r -> System.out.printf("firstId: %d, secondId: %d%n", r.getFirstId(), r.getSecondId())); } }
关键逻辑说明
- 异常校验:通过Stream过滤出
firstMap中未在secondMap出现的键,若集合非空则抛出明确的参数异常,快速定位问题。 - 映射构建:因已完成校验,无需额外过滤,直接基于
firstMap构建finalMap,逻辑更简洁可靠。 - 赋值优化:原嵌套循环时间复杂度为
O(n*m),优化后通过finalMap.get()直接取值,时间复杂度降至O(n),执行效率大幅提升。
异常触发示例
当firstMap存在secondMap没有的键(如示例中的33L),运行时会抛出:
Exception in thread "main" java.lang.IllegalArgumentException: secondMap中缺失必填键: [33]
内容的提问来源于stack exchange,提问作者Dovile Barkauskaite
相关产品推荐
相关产品推荐

