Iterate a map using forEach

 194 total views,  2 views today

In this tutorial let us see how to iterate a map using forEach loop in Java

Prerequisite:Install Java 8

Using for-loop,

 Map<Integer,String> map = new HashMap<>();
 map.put(1, "Value 1");
 map.put(2, "Value 2");
 map.put(3, "Value 3");
 map.put(4, "Value 4");
        
 for(Entry<Integer,String> entry :map.entrySet()) {
        System.out.println("Key is "+entry.getKey()+" and Value is "+entry.getValue());
 }

Using forEach,

Map<Integer,String> map = new HashMap<>();
map.put(1, "Value 1");
map.put(2, "Value 2");
map.put(3, "Value 3");
map.put(4, "Value 4");
              
map.forEach((k,v) -> System.out.println("Key is "+k+" and Value is "+v));

Key points for forEach

1. ForEach loop accepts lambda expressions or functions.

2. ForEach uses an internal iterator.

3.Developer can focus only on the logic rather than controlling the iteration.

Please refer How to use forEach for more information.

Java 8 forEach official documentation.

Thanks for reading.Please provide your valuable comments for this tutorial.

About the Author

Rajasekar

Hey There, My name is Rajasekar and I am the author of this site. I hope you are liking my tutorials and references. Programming and learning new technologies are my passion. The ultimate idea of this site is to share my knowledge(I am still a learner :)) and help you out!. Please spread your words about us (staticreference.com) and give a thumbs up :) Feel free to contact me for any queries!.