1. Introduction
In this article, I will show you how to traverse the Map in 7 different ways. Map is an interface that stores key-value pair.
2. 7 ways to traverse Map
- Using Map.keySet()
- Using Map.keySet().iterator()
- Using Map.entrySet()
- Using Map.entrySet().iterator()
- Using forEach()
- Using entrySet Stream
- Using keySet Stream
Example map to use for traversals:
Map<Integer, String> numberMap = new HashMap<>(); numberMap.put(Integer.valueOf(1), "One"); numberMap.put(Integer.valueOf(2), "Two"); numberMap.put(Integer.valueOf(3), "Three"); numberMap.put(Integer.valueOf(4), "Four");
3. Using Map.keySet()
keySet() is one of the Collection views method to see the data in Map. keySet() returns the Set of keys and we can get the value of keys by get(Object key) method.
Set<Integer> keySet = numberMap.keySet(); for (Integer key : keySet) { System.out.println(key + " " + numberMap.get(key)); }
4. Using Map.keySet().iterator()
In this method we take iterator of set and then traverse the map.
Iterator<Integer> keySet = numberMap.keySet().iterator(); while (keySet.hasNext()) { Integer K = keySet.next(); System.out.println(K + " " + numberMap.get(K)); }
5. Using Map.entrySet()
entrySet is another view that is provided by Map Interface. entrySet returns the Set of Map.Entry. We can then traverse using the enhanced for loop.
Set<Map.Entry<Integer, String>> entries = numberMap.entrySet(); for (Entry<Integer, String> entry : entries) { System.out.println(entry.getKey() + " " + entry.getValue()); }
6. Using Map.entrySet().iterator()
entrySet is another view that is provided by Map Interface. entrySet returns the Set of Map.Entry. Then we take the iterator for the Entry<K,V> and iterate through the Map.
Iterator<Entry<Integer, String>> entries = numberMap.entrySet().iterator(); while (entries.hasNext()) { Entry<Integer, String> entry = entries.next(); System.out.println(entry.getKey() + " " + entry.getValue()); }
7. Using forEach()
As of Java 8 we can traverse Map using Lambda Operator. The forEach method is a default method added in Map interface that accepts BiConsumer i.e. Consumer with two arguments.
numberMap.forEach((k, v) -> System.out.println(k + " " + v));
8. Using entrySet stream
numberMap .entrySet() .stream() .forEach(entry -> System.out.println(entry.getKey()+" "+entry.getValue()));
9. Using keySet Stream
numberMap .keySet() .stream() .forEach(intVal -> System.out.println( intVal+" "+numberMap.get(intVal)));
10. Conclusion
In this article we saw several ways to traverse a Map. Try this different methods out.