有这么一个小需求,有 2 个 List,但是我们希望返回 Map。
List 1 的数据到大于 List 2 中的数据。
返回 List1 的 map,如果 List 中的数据在 List 2 中存在的话,Map 的值是 True,如果不存在的话,是 False。
List1 和 List2 中的元素都是整数。
Stream
我们使用了 Java 提供的 Stream,当然你也可以用 For 循环。
下面的 map1 和 map 2 是等价的。
List<Integer> reqIds = Arrays.asList(1, 2);
List<Integer> reqs = Arrays.asList(1);
Map<Integer, Boolean> map1 = reqIds.stream().collect(Collectors.toMap(Function.identity(), item -> reqs.contains(item)));
Map<Integer, Boolean> map2 = reqIds.stream().collect(Collectors.toMap(Function.identity(), reqs::contains));
log.debug("Map Size {}",map2);
然后验证下结果。
文章展示了如何使用Java的StreamAPI将两个List转换成Map,其中Key来自List1,Value表示List1的元素是否存在于List2中。通过`collect`方法结合`Collectors.toMap`,可以简洁地创建这个映射关系。
3027

被折叠的 条评论
为什么被折叠?



