简体   繁体   English

如何比较两个哈希图/哈希表以仅找到唯一键

[英]how to compare two hashmap/hashtable to find only unique key

Hashtable h1=new Hashtable<>();
    h1.put(1, "abc");
    h1.put(2, "xyz");
    h1.put(26, "jhd");


    Hashtable h2=new Hashtable<>();
    h2.put(1, "da");
    h2.put(2, "bfdsae");
    h2.put(8, "sdasd");

    Hashtable h3= new Hashtable<>();
     below two output musst add in h3.

expected O/P is:- 8, "sdasd" 26, "jhd" when i will compare two hashtable to each other above required output has to be produced.预期的 O/P 是:- 8, "sdasd" 26, "jhd" 当我将两个哈希表相互比较时,必须产生所需的输出。

Using google guava you could get this with Maps.difference :使用 谷歌番石榴,你可以通过Maps.difference得到这个:

MapDifference<Integer, String> difference = Maps.difference(h1, h2);

h3.putAll(difference.entriesOnlyOnLeft());
h3.putAll(difference.entriesOnlyOnRight());

It gives you {8=sdasd, 26=jhd} in h3它在h3为您提供{8=sdasd, 26=jhd}

Traverse h1 and check if the exists in h2, if it doesn't,then put in h3.遍历h1并检查h2中是否存在,如果不存在,则放入h3。 Similarly, Traverse h2 and check if the exists in h1, if it doesn't,then put in h3.同样,遍历h2并检查h1中是否存在,如果不存在,则放入h3。

    Hashtable h1=new Hashtable<>();
        h1.put(1, "abc");
        h1.put(2, "xyz");
        h1.put(26, "jhd");


        Hashtable h2=new Hashtable<>();
        h2.put(1, "da");
        h2.put(2, "bfdsae");
        h2.put(8, "sdasd");

        Hashtable h3= new Hashtable<>();
        Set<String> keys = h1.keySet();
        for(String k: keys){
            if(!h2.containsKey(k)) {
                h3.put(k, h1.get(k));
            }
        }
        Set<String> keysH2 = h2.keySet();
        for(String k: keys){
            if(!h1.containsKey(k)) {
                h3.put(k, h2.get(k));
            }
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM