Java Dailly Tip: How can I iterate through the maps?

Java Dailly Tip: How can I iterate through the maps?

I use Java Maps a lot, but can't iterate well over them. How to do it efficiently? There are several ways to work with Maps in Java. Here are the most popular of them.

Solution

There are several ways to work with Maps in Java. Here are the most popular of them.

  1. Using iterator and Map.Entry
    long i = 0;
    Iterator> it = map.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry pair = it.next();
        i += pair.getKey() + pair.getValue();
    }
    
  2. Using foreach and Map.Entry
    long i = 0;
    for (Map.Entry pair : map.entrySet()) {
        i += pair.getKey() + pair.getValue();
    }
    
  3. Using forEach
    final long[] i = {0};
    map.forEach((k, v) -> i[0] += k + v);
    
  4. Using keySet and foreach
    long i = 0;
    for (Integer key : map.keySet()) {
        i += key + map.get(key);
    }
    
  5. Using keySet and iterator
    long i = 0;
    Iterator itr2 = map.keySet().iterator();
    while (itr2.hasNext()) {
        Integer key = itr2.next();
        i += key + map.get(key);
    }
    
  6. Using for and Map.Entry
    long i = 0;
    for (Iterator> entries = map.entrySet().iterator(); entries.hasNext(); ) {
        Map.Entry entry = entries.next();
        i += entry.getKey() + entry.getValue();
    }
    
  7. Using the Java Stream API
    final long[] i = {0};
    map.entrySet().stream().forEach(e -> i[0] += e.getKey() + e.getValue());
    
  8. Using the Java Stream API parallel
    final long[] i = {0};
    map.entrySet().stream().parallel().forEach(e -> i[0] += e.getKey() + e.getValue());
    
  9. Using IterableMap of Apache Collections
    
    long i = 0;
    MapIterator it = iterableMap.mapIterator();
    while (it.hasNext()) {
        i += it.next() + it.getValue();
    }
    
  10. Using MutableMap of Eclipse (CS) collections
    final long[] i = {0};
    mutableMap.forEachKeyValue((key, value) -> {
        i[0] += key + value;
    });
    

Share this Post