Categories
Java

8 Ways to Iterate Each Entry of Java Map

Java collection framework has Map interface and several implementation classes like HashMap, LinkedHashMap, TreeMap, ConcurrentHashMap. Map one of the most used interface used to store and operate on key-value pairs.

To iterate all entries of a Map, there are several ways as given below.

1- Using foreach and entrySet method

for (Map.Entry<String, Integer> entry : map.entrySet()) {
    System.out.println(entry.getKey());
    System.out.println(entry.getValue());
}

2- Using map.forEach method

map.forEach((key, value) -> {
    System.out.println(key);
    System.out.println(value);
});

3- Using Iterator and Map.Entry with while loop

Iterator<Map.Entry<String, Integer>> it = map.entrySet().iterator();
while (it.hasNext()) {
    Map.Entry<String, Integer> entry = it.next();
    System.out.println(entry.getKey());
    System.out.println(entry.getValue());
}

4- You iterate on the basis of the keyset only Using keySet and foreach

for (String key : map.keySet()) {
    System.out.println(key);
    System.out.println(map.get(key));
}

5- You iterate on the basis of the keyset only Using keySet and while loop and iterator

Iterator<String> itr = map.keySet().iterator();
while (itr.hasNext()) {
    String key = itr.next();
    System.out.println(key);
    System.out.println(map.get(key));
}

6- Using for and Map.Entry

for (Iterator<Map.Entry<String, Integer>> entries = map.entrySet().iterator(); entries.hasNext(); ) {
    Map.Entry<String, Integer> entry = entries.next();
    System.out.println(entry.getKey());
    System.out.println(entry.getValue());
}

7- Using Java 8 stream

map.entrySet().stream().forEach(e -> {
    System.out.println(e.getKey());
    System.out.println(e.getValue());
    });

8- Using Java 8 stream parrellel

map.entrySet().stream().parallel().forEach(e -> {
    System.out.println(e.getKey());
    System.out.println(e.getValue());
    });

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.