What is the best way to iterate two hashmap in same loop in java?
Solution 1
There really isn't a better option than
for (Map.Entry<String, String> entry1 : map1.entrySet() {
String key = entry1.getKey();
String value1 = entry1.getValue();
String value2 = map2.get(key);
// do whatever with value1 and value2
}
Solution 2
Depending on what exactly you're trying to do, there are several reasonable options:
-
Just compare the contents of two maps
Guava provides a
Maps.difference()
utility that gives you aMapDifference
instance letting you inspect exactly what is the same or different between two maps. -
Iterate over their entries simultaneously
If you just want to iterate over the entries in two maps simultaneously, it's no different than iterating over any other
Collection
. This question goes into more detail, but a basic solution would look like this:Preconditions.checkState(map1.size() == map2.size()); Iterator<Entry<String, String>> iter1 = map1.entrySet().iterator(); Iterator<Entry<String, String>> iter2 = map2.entrySet().iterator(); while(iter1.hasNext() || iter2.hasNext()) { Entry<String, String> e1 = iter1.next(); Entry<String, String> e2 = iter2.next(); ... }
Note there is no guarantee these entries will be in the same order (and therefore
e1.getKey().equals(e2.getKey())
may well be false). -
Iterate over their keys to pair up their values
If you need the keys to line up, iterate over the union of both maps' keys:
for(String key : Sets.union(map1.keySet(), map2.keySet()) { // these could be null, if the maps don't share the same keys String value1 = map1.get(key); String value2 = map2.get(key); ... }
Spartan
Updated on July 24, 2022Comments
-
Spartan almost 2 years
What's the best way to iterate over the below two maps together? I want to compare two maps values which are strings and have to get the keys and values.
HashMap<String, String> map1; HashMap<String, String> map2;
-
Ankur Singhal almost 9 yearsmatch what, insertion order will not be same in two
hashmap
, so element by element comparison not possible. EIther iterate first , and get the key values from 2nd and compare -
Paraneetharan Saravanaperumal almost 9 yearsis it need to compare only maps value , not keys right??
-
Spartan almost 9 yearsHi ankur /ParaSara, I have to compare values in both maps.
-
Patricia Shanahan almost 9 yearsMaybe you should be using LinkedHashMap, so that the iterators will run in order of insertion?
-
Kenneth Clark almost 9 yearspossible duplicate of How to compare two maps by their values
-
Spartan almost 9 yearsthanks Patricia.I want to fetch the keys and values also in string. @Kenneth-its not duplicate of that..i want to know the process of iteration
-
-
Louis Wasserman over 5 yearsIf they're both LHMs and you know they have the same iteration order, you could use a pair of iterators in lockstep.