Java 8 | forEach with examples

 329 total views,  2 views today

In this tutorial let us learn about Java 8 forEach with examples.

The main use of forEach is to iterate over a collection. There are multiple ways to iterate a collection but in Java 8, the new forEach statement has made it look so simple and legible.

Please refer How to use forEach for more information.

Iterate a list – Example

Prior to Java 8,below is the way to iterate a list of objects.

List<String> list = new ArrayList<String>();
list.add("Item 1");
list.add("Item 2");
list.add("Item 3");
list.add("Item 4");

for (String str : list) {
   System.out.println(str);
}

But now, forEach can be used to iterate a list.

list.forEach(item -> System.out.println(item));

In the above code ,we have used lambda expression with forEach to iterate and print the elements of list.We can further shorten the code by using method reference.

list.forEach(System.out::println);

Please refer Iterate a list using forEach for more examples.

Iterate a map – Example

Prior to Java 8,below is the way to iterate a map

Map<Integer, String> map = new HashMap<>();
map.put(1, "Text 1");
map.put(2, "Text 2");
map.put(3, "Text 3");

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

By using forEach,

map.forEach((key, value) -> System.out.println("Key :" + key + " value : " + value));
	

Please refer Iterate a map using forEach for more examples.

Please refer External iterator vs internal iterators to know how forEach controls iteration.

Java 8 forEach official documentation.

Thanks for reading.Please provide your valuable comments.

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!.