views:

278

answers:

2

I have two HashMaps: FOO & BAR.

HashMap FOO is a superset of HashMap BAR.

How do I find out what 'keys' are missing in HashMap BAR (i.e. exists in FOO but not BAR)?

+11  A: 
Set missing = new HashSet(foo.keySet());
missing.removeAll(bar.keySet());
erickson
+1 for making a new set. foo.keySet().removeAll() will actually modify the foo map.
Jherico
+7  A: 

If you're using google-collections (and realistically I think it should be on the classpath of more or less every non-trivial Java project) it's just:

Set<X> missing = Sets.difference(foo.keySet(), bar.keySet();
Cowan
You can also use `MapDifference<Key, Value> mapDiff = Maps.difference(FOO, BAR);` and examine the resulting object for a full description of how the maps differ.
Kevin Bourrillion
Oh wow. Haven't looked at MapDifference before, thanks Kevin.
Cowan