Iterate a list using forEach

 211 total views,  2 views today

In this tutorial let us see how to iterate a list using forEach in Java 8.

Prerequisite:Install Java 8 to use forEach

The main purpose of forEach is to iterate over a collection and let us now focus on iterating a list.

Using for-loop to iterate a list

 List<String> list  = new ArrayList<>();
 list.add("Apple");
 list.add("Orange");
 list.add("Banana");
 list.add("Grapes");
       
 //Iterate and print using for-loop
 for(String item:list) {
       System.out.println(item);
 }

Using forEach,

 List<String> list  = new ArrayList<>();
 list.add("Apple");
 list.add("Orange");
 list.add("Banana");
 list.add("Grapes");
       
 //Iterate and print each element
 list.forEach(item -> System.out.println(item));

Key points for foreach loop

1. ForEach accepts lambda expressions or functions.

2. ForEach loop 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!.