A friendly place for programming greenhorns!
Big Moose Saloon
Register / Login
Win a copy of
Head First Android
this week in the
Java in General
comparing keys of two hashmaps
Joined: Nov 29, 2004
Feb 08, 2010 21:20:50
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
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.
Joined: Aug 11, 2007
Feb 08, 2010 21:35:57
If you use the Google Collections package, it has functions to do the usual intersection, union, and difference functions for sets.
Vivek K Singh
Joined: Dec 22, 2009
Feb 08, 2010 23:05:32
You do not need to loop thru both the maps, you can do something like:
for (Map.Entry<String, String> me : hashmap1.entrySet()) // assuming your map is Map<String, String> if(hashmap2.containsKey(me.getKey())) System.out.println("Found Duplicate -> " + me.getKey());
This will get all keys from the hashmap1 and compare to the hashmap2 and print duplicates...
Joined: Oct 27, 2005
Feb 09, 2010 01:31:50
Or use keySet() in combination with the bulk operators:
// union Set<String> union = new HashSet<String>(h1.keySet()); union.addAll(h2.keySet()); // h1 - h2 Set<String> diff1 = new HashSet<String>(h1.keySet()); diff1.removeAll(h2.keySet()); // h2 - h1 Set<String> diff2 = new HashSet<String>(h2.keySet()); diff1.removeAll(h1.keySet()); // intersection Set<String> intersect = new HashSet<String>(h1.keySet()); intersect.retainAll(h2.keySet());
SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6 - OCEJPAD 6
How To Ask Questions
How To Answer Questions
Did you see how Paul
cut 87% off of his electric heat bill with 82 watts of micro heaters
subject: comparing keys of two hashmaps
String is not working as i supposed it to work
Read a property file in JSTL
Please explain the output
addition of two Hash maps
how object.clone() is different then direct reference assignment
All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter
| Powered by
Copyright © 1998-2015