【问题标题】:Lambda for comparing two lists of map id fields for missing ids用于比较两个地图 ID 字段列表以查找缺失 ID 的 Lambda
【发布时间】:2020-11-29 18:09:57
【问题描述】:

我有两个地图列表,每个地图都有一个 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());

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

【问题讨论】:

  • 对于初学者,您为什么使用e.entrySet().stream() 而不是e.get("id")

标签: java lambda java-8 stream


【解决方案1】:

如果您想从collectionA 中过滤出collectionB 中不存在的项目映射,请迭代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());

【讨论】:

  • 感谢这对我有很大帮助。我不太确定为什么);收藏家.toList();在“外部”/过去的分号处工作。 noneMatch 很棒,我不知道那里有。
猜你喜欢
  • 2011-12-21
  • 2021-04-15
  • 2022-09-27
  • 1970-01-01
  • 2019-08-04
  • 1970-01-01
  • 2016-05-11
  • 2021-12-23
  • 2017-11-03
相关资源
最近更新 更多