简体   繁体   中英

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.

Using google guava you could get this with 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

Traverse h1 and check if the exists in h2, if it doesn't,then put in h3. Similarly, Traverse h2 and check if the exists in h1, if it doesn't,then put in 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));
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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