Spartan
Spartan

Reputation: 3381

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;

Upvotes: 11

Views: 33439

Answers (4)

juggernaut
juggernaut

Reputation: 126

You can do something like:

for (String key : map1.keySet()) {
  if (map2.containsKey(key)) {
    // do whatever
  } else {
    // map2 doesn't have entry with map1 key
  }
}

Upvotes: 0

KJTester
KJTester

Reputation: 407

My case if maps are the same sizes

IntStream.range(0, map1.size()).forEach(i -> map1.get(i).equals(map2.get(i));

Upvotes: 0

dimo414
dimo414

Reputation: 48814

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);
      ...
    }
    

Upvotes: 6

Louis Wasserman
Louis Wasserman

Reputation: 198033

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 
}

Upvotes: 27

Related Questions