Lambda,用于比较两个映射 ID 字段列表以查找缺失的 ID



我有两个映射列表,每个映射作为一个id字段。我需要将这两个列表相互比较,以查找集合 B 中缺少的 ID(下面的"7777")

List<Map<String, Object>> collectionA = new ArrayList<Map<String, Object>>() {{
add(new HashMap<String, Object>() {{ put("id", "5555"); }});
add(new HashMap<String, Object>() {{ put("id", "6666"); }});
add(new HashMap<String, Object>() {{ put("id", "7777"); }});
add(new HashMap<String, Object>() {{ put("id", "8888"); }});
}};
List<Map<String, Object>> collectionB = new ArrayList<Map<String, Object>>() {{
add(new HashMap<String, Object>() {{
add(new HashMap<String, Object>() {{ put("id", "5555"); }});
add(new HashMap<String, Object>() {{ put("id", "6666"); }});
add(new HashMap<String, Object>() {{ put("id", "8888"); }});
}});
}};

我真的很想了解更多关于 stream() 的信息,所以任何帮助将不胜感激。正如你所知道的,我真的不确定从哪里开始:

我开始走这条路,但似乎这不是正确的方法。

List<String> bids = collectionB.stream()
.map(e -> e.entrySet()
.stream()
.filter(x -> x.getKey().equals("id"))
.map(x -> x.getValue().toString())
.collect(joining("")
)).filter(x -> StringUtils.isNotEmpty(x)).collect(Collectors.toList());

我想这让我得到了两个可以比较的字符串列表,但似乎这不是最佳方法。任何帮助,不胜感激。

如果要从collectionB中不存在的collectionA中过滤项目的映射,请迭代collectionA并检查collectionB中任何Map中是否存在的每个条目,最后收集Map中不存在的条目collectionB

List<Map<String,String>> results = collectionA.stream()
.flatMap(map->map.entrySet().stream())
.filter(entry->collectionB.stream().noneMatch(bMap->bMap.containsValue(entry.getValue())))
.map(entry-> Collections.singletonMap(entry.getKey(),entry.getValue()))
.collect(Collectors.toList());

最新更新