【问题标题】:How to Compare a Key of a HashMap with a Set?如何将 HashMap 的键与集合进行比较?
【发布时间】:2021-09-14 12:00:43
【问题描述】:

我有一个HashMap

HashMap<Integer,Integer> hashMap = new HashMap<Integer,Integer>();

还有一个SetSets:

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

我想检查 HashMap 的 3 个键是否包含 Set 的 3 个元素,如果是,请检查值是否相等。

例如:

hashMap.put(0,1);
hashMap.put(1,1);
hashMap.put(2,1);
return true;

hashMap.put(4,2);
hashMap.put(5,2);
hashMap.put(12,2);
return false;

stream() 是否有可能的解决方案?

【问题讨论】:

  • 所以这是this的反面?
  • 看起来他在一些编程练习中寻求解决方案。

标签: java dictionary hashmap set java-stream


【解决方案1】:

首先,我会检查地图条目并确保它们都与键匹配,因为无论设置如何都可以检查这一点。您可以通过流式传输条目并使用allMatch 来实现此目的。然后,您可以流式传输这些集合,并检查每个集合的大小是否相同,并且所有键都匹配:

return hashMap.entrySet()
              .stream()
              .allMatch(e -> e.getKey().equals(e.getValue())) &&
       set.stream()
          .anyMatch(s -> s.size() == hashMap.size() && s.containsAll(hashMap.keySet()));

【讨论】:

    【解决方案2】:

    试试这个。

    static boolean test(HashMap<Integer, Integer> hashMap, Set<Set<Integer>> set) {
        return set.stream()
            .anyMatch(s -> hashMap.keySet().containsAll(s) &&
                s.stream().map(k -> hashMap.get(k)).distinct().count() == 1);
    }
    

    Set<Set<Integer>> set = Set.of(Set.of(0, 1, 2), Set.of(3, 4, 5));
    
    HashMap<Integer, Integer> hashMap1 = new HashMap<>(Map.of(0, 1, 1, 1, 2, 1));
    System.out.println(hashMap1 + " : " + test(hashMap1, set));
    
    HashMap<Integer, Integer> hashMap2 = new HashMap<>(Map.of(4, 2, 5, 2, 12, 2));
    System.out.println(hashMap2 + " : " + test(hashMap2, set));
    

    输出:

    {0=1, 1=1, 2=1} : true
    {12=2, 4=2, 5=2} : false
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-21
      • 1970-01-01
      • 2021-12-13
      • 1970-01-01
      相关资源
      最近更新 更多