如何检查 java 哈希表是否包含来自另一个哈希表的键值对

How to check if java hashtable contains key-value pairs from another hashtable

是否有任何内置的 java 方法来检查一个散列 table 是否包含另一个散列中存在的所有键值对?

例如:

h1={{0,1},{1,4},{2,5},{3,6}}
h2={{0,1},{2,5}}

在这种情况下,h1 确实包含来自 h2 的键值对。

下面是一个小示例程序,用于演示如何匹配 2 个不同映射的键或键和值:

    public class HashMapMatch {

        public boolean hasMatchingKey(String key, Map m1, Map m2){
            return m1.containsKey(key) && m2.containsKey(key);
        }

        public boolean hasMatchingKeyAndValue(String key, Map m1, Map m2){
            if(hasMatchingKey(key, m1, m2)){
                return m1.get(key).equals(m2.get(key));
            }
            return false;
        }

        public static void main(String[] args) {
            HashMapMatch matcher = new HashMapMatch();
            Map<String, Integer> map1 = new HashMap<>();
            map1.put("One",1);
            map1.put("Two",22);
            map1.put("Three",3);

            Map<String, Integer> map2 = new HashMap<>();
            map2.put("One",1);
            map2.put("Two",2);
            map2.put("Four",4);

            System.out.println("Has matching key? :" + matcher.hasMatchingKey("One", map1, map2));
            System.out.println("Has matching key? :" + matcher.hasMatchingKey("Two", map1, map2));
            System.out.println("Has matching key? :" + matcher.hasMatchingKey("Three", map1, map2));

            System.out.println("Has matching key value: :" + matcher.hasMatchingKeyAndValue("One", map1,map2));
            System.out.println("Has matching key value: :" + matcher.hasMatchingKeyAndValue("Two", map1,map2));

        }
    }

产生输出:

Has matching key? :true
Has matching key? :true
Has matching key? :false
Has matching key value: :true
Has matching key value: :false

Hashtable 上没有方法可以让你直接检查这个,但你可以在每个 Hashtable 上使用 entrySet() 方法来获得它的 Set 所有键值对。

然后你可以使用 containsAll() 来查看其中一个是否是另一个的子集,因为它

Returns true if this set contains all of the elements of the specified collection. If the specified collection is also a set, this method returns true if it is a subset of this set.

例如

//  h1={{0,1},{1,4},{2,5},{3,6}}
    Hashtable<Integer, Integer> h1 = new Hashtable<>();
    h1.put(0, 1);
    h1.put(1, 4);
    h1.put(2, 5);
    h1.put(3, 6);

//  h2={{0,1},{2,5}}
    Hashtable<Integer, Integer> h2 = new Hashtable<>();
    h2.put(0, 1);
    h2.put(2, 5);

    Set<Entry<Integer, Integer>> e1 = h1.entrySet();
    Set<Entry<Integer, Integer>> e2 = h2.entrySet();

    System.out.println(e2.containsAll(e1));  // false
    System.out.println(e1.containsAll(e2));  // true