【问题标题】:Can you compare the Keys of a HashMap with a Set?你能将 HashMap 的 Keys 与 Set 进行比较吗?
【发布时间】:2021-09-14 04:30:39
【问题描述】:

我有一个哈希图

 HashMap<Integer,Integer> hashmap = new HashMap<Integer,Integer>();
    hashmap.put(0,1);
    hashmap.put(1,1);
    hashmap.put(2,1);
    hashmap.put(3,2);

还有一个集合

 Set<Set<Integer>> set = Set.of(Set.of(0, 1, 2), Set.of(3, 4, 5), Set.of(6, 7, 8));

现在我想将我的 hashmap 与集合进行比较,并输出包含所有 3 个键且值相同的集合。例如 hashmap {0=1, 1=1, 2=1, 3=2} 应该输出集合 (0,1,2)。 我尝试使用流():

hashmap.entrySet().stream().filter(e-> e.getValue()==1).map(Map.Entry::getKey).forEach(System.out::println);

但我不知道如何相互比较

 Stream<Set<Integer>> streamsets = set.stream();
  streamsets.forEach(System.out::println);

【问题讨论】:

  • 澄清一下,你想在set中找到一个集合S,这样S中的每个元素都是映射hashmap的一个键,与S的每个元素关联的值是一样吗?
  • @Sweeper 完全正确!

标签: java nested hashmap set java-stream


【解决方案1】:

您应该流式传输set 而不是地图:

set.stream().filter(
        // s has to be a subset of the map's keys
        s -> hashmap.keySet().containsAll(s) &&

        // then we look up the associated values
        s.stream().map(hashmap::get)
            .distinct() // only keep distinct values
            .limit(2).count() == 1 // there should only be one distinct value
    ).forEach(System.out::println);

【讨论】:

  • ok 工作正常,是否也可以以某种方式标记输出,以查看哪个集合属于 hashmap 的值 (1,2)?类似于:[set1] + hashset.getValue [set2] + hashset.getValue
  • @lz01 是的,而不是forEach,您可以使用Collectors.toMap:将每个集合用作键,并将hashmap.get 的结果用作值。这将涉及再次访问hashmap。我想不出只访问一次地图的流解决方案。
  • 好的,我不确定我是否正确理解了你的答案,你能在上面的代码中实现它吗?
  • 我认为这不是一个特别好的解决方案,而且它也不是您原始问题的一部分,因此我不想将其添加到我的答案中。我的意思不是forEach,而是.collect(Collectors.toMap(s -&gt; s, s -&gt; hashmap.get(s.iterator().next())))。这会给你一个Map&lt;Set&lt;Integer&gt;, Integer&gt;,你可以打印出来。 @lz01
最近更新 更多