How to iterate java map with different examples

0
2126

In this article we are going to see how to iterate java map in different approaches with simple examples, we will go through different ways of iterating map in java before java 8 and from Java 8 and above. And also we are going to see usage of keySet(), values(), entrySet(), forEach() methods of Java Map interface. These methods are common for any Map implementation classes.

1. Different ways of Iterate a map

Following are the most commonly used approaches  to iterate any map in java.

  1. Iterate using collections Iterator.
  2. Iterate using keySet() through enhanced for-each loop.
  3. Iterate using entrySet() through enhanced for-each loop.
  4. Iterate using java 8 forEach() method, functional style.
  5. Iterate using java 8 Stream forEach() method.

2. Ways to Iterating a map before Java 8

2.1. Using collections Iterator

We can use Iterator to get objects one by one from any collection object. We can apply Iterator concept for any collection object and it is a universal cursor. Following example illustrates  how to iterate a Map using Iterator and also demonstrates keySet()values() methods of map.

public class IterateMapBeforeJava8IteratorDemo {

	public static void main(String[] args) {
		
		Map<Integer, String> hashMap1 = new HashMap<Integer, String>();
		hashMap1.put(7, "Peter");
		hashMap1.put(5, "Philip");
		hashMap1.put(2, "Martin");
		
		// Iterate map using Iterator
		Iterator<Integer> iterator = hashMap1.keySet().iterator();
		
		System.out.println("Iterating map using iterator");
		System.out.println("----------------------- \n");
		while (iterator.hasNext()) {
			Integer key = iterator.next();
			System.out.println("Map key : "+key+", Map Value: "+hashMap1.get(key));
		}
		System.out.println("----------------------- \n");
		
		// verify whether values contains Martin in Map
		System.out.println("Is Martin value exist in map values? "+ hashMap1.values().contains("Martin"));
	}
}

Output :

Iterating map using Iterator
----------------------- 

Map key : 2, Map Value: Martin
Map key : 5, Map Value: Philip
Map key : 7, Map Value: Peter
----------------------- 

Is Martin value exist in map values? true

2.2. Iterate a map using keySet()

public class IterateMapUsingKeySetDemo {

	public static void main(String[] args) {
		Map<Integer, String> hashMap1 = new HashMap<Integer, String>();
		hashMap1.put(7, "Peter");
		hashMap1.put(5, "Philip");
		hashMap1.put(2, "Martin");
		
		for(Integer key : hashMap1.keySet())
		    System.out.println(key + " "+ hashMap1.get(key));
	}
}

Output :

2 Martin
5 Philip
7 Peter

2.3. Iterate a map using entrySet()

What is Map Entry? :  Entry is a child interface of Map and it holds key and value.

What is Map? :  In general a map is a collection of entries. In this example lets see how we iterate a map using entrySet() using for-each loop.

public class IterateMapByEntrySetDemo {

	public static void main(String[] args) {
		
		Map<Integer, String> hashMap1 = new HashMap<Integer, String>();
		hashMap1.put(7, "Peter");
		hashMap1.put(5, "Philip");
		hashMap1.put(2, "Martin");
		
		for(Map.Entry<Integer, String> entry : hashMap1.entrySet())
		    System.out.println(entry.getKey() + " "+ entry.getValue());
	}
}

Output :

2 Martin
5 Philip
7 Peter

3. Iterate map in Java 8 and above

3.1. Iterate map using java 8 forEach()

forEach() introduced in Java 8 to iterate collections. To know more about java iterator() method read article Java forEach method.

public class IterateMapJava8ForeachDemo {

	public static void main(String[] args) {
		
		Map<Integer, String> hashMap = new HashMap<Integer, String>();
		hashMap.put(7, "Peter");
		hashMap.put(5, "Philip");
		hashMap.put(2, "Martin");
		
		hashMap.forEach( (key, value) -> {
			System.out.println("Key : " + key + ", value : " + value);
		});
	}
}

Output :

Key : 2, value : Martin
Key : 5, value : Philip
Key : 7, value : Peter

3.1. Iterate map using Stream forEach()

public class IterateMapJava8StreamDemo {

	public static void main(String[] args) {
		
		Map<Integer, String> hashMap = new HashMap<Integer, String>();
		hashMap.put(7, "Peter");
		hashMap.put(5, "Philip");
		hashMap.put(2, "Martin");
		
		hashMap.entrySet().stream().forEach(e ->
		   System.out.println("Key : " + e.getKey() + ", value : " + e.getValue())
         );
	}
}

Output :

Key : 2, value : Martin
Key : 5, value : Philip
Key : 7, value : Peter

Conclusion

In this article we have shown the different ways of iterating a map. Apart from these approaches we can iterate using standard for loop as well, in java 5 introduced a special loop called enhanced for-each loop to iterate over collections and arrays, since java 5 for-each loop is most commonly used approach to iterate any collection. Now collections forEach() method Stream forEach() most popular since Java 8.

LEAVE A REPLY

Please enter your comment!
Please enter your name here