Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to iterate two hashmap in same loop in java?

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;
like image 280
Spartan Avatar asked Jun 18 '15 04:06

Spartan


2 Answers

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 
}
like image 78
Louis Wasserman Avatar answered Sep 21 '22 09:09

Louis Wasserman


Depending on what exactly you're trying to do, there are several reasonable options:

  1. Just compare the contents of two maps

    Guava provides a Maps.difference() utility that gives you a MapDifference instance letting you inspect exactly what is the same or different between two maps.

  2. 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).

  3. 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);
      ...
    }
    
like image 43
dimo414 Avatar answered Sep 21 '22 09:09

dimo414