- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to iterate a List using for-Each Loop in Java?
The List interface extends Collection interface and is an important member of Java Collections Framework. List interface declares the behavior of a collection that stores a sequence of elements. The most popular implementation of List interface is ArrayList. User of a list has quite precise control over where an element to be inserted in the List. These elements are accessible by their index and are searchable.
A forEach loop helps in iterating an array or collection of objects. As List contains objects, it can be easily iterated using forEach loop. Following code snippet shows how to use a forEach loop to iterate a list.
for (Integer integer : list) { System.out.print(integer + " "); }
List interface also provides a forEach() method which can be used to iterate the list as shown below −
list.forEach(i -> {System.out.print(i + " ");});
Example 1
Following is the example showing forEach loop to iterate the list −
package com.tutorialspoint; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class CollectionsDemo { public static void main(String[] args) { List<String> list = new ArrayList<>(Arrays.asList("A", "B", "C")); for (String string : list) { System.out.print(string + " "); } } }
Output
This will produce the following result −
A B C
Example 2
Following is the example showing List.forEach method to iterate the list −
package com.tutorialspoint; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class CollectionsDemo { public static void main(String[] args) { List<String> list = new ArrayList<>(Arrays.asList("A", "B", "C")); list.forEach(i -> {System.out.print(i + " ");}); } }
Output
This will produce the following result −
A B C