How to compare value or keys in a hash table?

Suppose I have code

public static void main(String args[])
{
    Hashtable ht = new Hashtable();
    Hashtable ht2 = new Hashtable();
    for(int i=0;i<100;i++)
    {
        ht.put(i, new Integer (i));
    }
    for(int i=50;i<100;i++)
    {
        ht2.put(i, new Integer (i));
    }
}

If I wanted to compare two different hash tables, how will I do it in Java? EDIT: if I would like to compare a key or an actual value in a hash table

+3
source share
3 answers

This will print all common key / value pairs:

public static void main(String args[])
{
    Map<Integer, Integer> ht = new HashMap<Integer, Integer>();
    Map<Integer, Integer> ht2 = new HashMap<Integer, Integer>();
    for(int i=0;i<100;i++)
    {
        ht.put(i, i);
    }
    for(int i=50;i<100;i++)
    {
        ht2.put(i, i);
    }

    System.out.println("The following keys and values match:");

    for (Map.Entry<Integer, Integer> htEntries : ht.entrySet()) {
        if(ht2.containsKey(htEntries.getKey()) && ht2.get(htEntries.getKey()).equals(htEntries.getValue())){
            System.out.println("\tKey: " + htEntries.getKey() + " Value: " + htEntries.getValue());
        }
    }
}
+2
source

If you want to know what combinations of key values ​​they have, use something like

 HashSet<Entry<Integer, Integer>> entries = new HashSet<Entry<Integer, Integer>>(
   table1.entrySet());
 entries.retainAll(table2.entrySet());

and entrieswill only have entries with the same keys and values ​​from both cards.

, FYI, Guava Maps.difference, , , , , , .

+1

If you want to compare that the two mappings are identical, use ht.equals(ht2).

To compare keys only, use ht.keySet().equals(ht2.keySet()).

Comparing values ​​is a bit more complicated and depends on your requirements. What are your requirements?

PS Hashtableis obsolete; HashMap<Integer,Integer>should be preferred in most cases.

0
source

All Articles