File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes comparing keys of two hashmaps Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "comparing keys of two hashmaps" Watch "comparing keys of two hashmaps" New topic
Author

comparing keys of two hashmaps

Mohit Sinha
Ranch Hand

Joined: Nov 29, 2004
Posts: 122
Hi All,

I want to identify the identical keys amongst two haspmaps (H1 and H2).
Also I need to identify elements of H1 not available in H2 and vice versa.

Currently I am using the HashMap interface containsKey method but have to do something like this

- loop throught all keys of H1 and H2.containsKey(h1_key)
- loop throught all keys of H2 and H1.containsKey(h2_key)

Ist there a better view to implement the same.


Thanks


Pat Farrell
Rancher

Joined: Aug 11, 2007
Posts: 3688

If you use the Google Collections package, it has functions to do the usual intersection, union, and difference functions for sets.
Vivek K Singh
Ranch Hand

Joined: Dec 22, 2009
Posts: 85

You do not need to loop thru both the maps, you can do something like:



This will get all keys from the hashmap1 and compare to the hashmap2 and print duplicates...


SCJP 6
Rob Spoor
Saloon Keeper

Joined: Oct 27, 2005
Posts: 18365

Or use keySet() in combination with the bulk operators:


SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
 
 
subject: comparing keys of two hashmaps
 
Threads others viewed
String is not working as i supposed it to work
Please explain the output
Read a property file in JSTL
addition of two Hash maps
how object.clone() is different then direct reference assignment
Two Laptop Bag

cast iron skillet 49er

more from paul wheaton's glorious empire of web junk: cast iron skillet diatomaceous earth rocket mass heater sepp holzer raised garden beds raising chickens lawn care CFL flea control missoula heat permaculture