Warm tip: This article is reproduced from serverfault.com, please click

java-Lambda,用于比较两个 mapID字段列表以查找缺少的ID

(java - Lambda for comparing two lists of map id fields for missing ids)

发布于 2020-11-29 18:09:57

我有两个 map列表,每个 map都作为一个ID字段。我需要将这两个列表相互比较,以从collectionB中找到丢失的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());

我想这使我进入了两个可以比较的字符串列表,但这似乎不是最佳方法。任何帮助表示赞赏。

Questioner
Justin
Viewed
0
32.9k 2020-11-30 21:49:51

如果要筛选项目的 map,从collectionA它们是不存在的collectionB,迭代collectionA和检查每个条目存在于任何的MapcollectionB,终于收集进入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());