Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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?
A List is an ordered collection or an interface that contains elements of similar types. Since the list is a collection object, we can iterate (or loop) a list using different control flow statements or an Iterator object.
This article will discuss one way to (i.e., using forEach loop) iterate over a list:
Iterate over a List Using forEach Loop
A forEach loop is a control flow statement that helps to iterate (or loop through) over a collections object.
As the List is an ordered collection, it can be easily iterated using a forEach loop or any other control flow statements such as for and while loops.
Example 1
In the following example, we iterate over a List (instantiating using ArrayList class) using a forEach loop to print each element one by one of the List {1, 2, 3, 4, 5}:
import java.util.ArrayList;
import java.util.List;
public class iterateOverList {
public static void main(String[] args) {
//instantiating a List using ArrayList class
List<Integer> list = new ArrayList<>();
//adding element to it
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
System.out.println("The list elements are: ");
//iterate over a list using for-each loop
for(Integer l: list){
System.out.println(l + " ");
}
}
}
The above program produces the following output:
The list elements are: 1 2 3 4 5
Example 2
In the example below, we use the forEach loop to iterate over a List (instantiating using Stack Class) to print each of its elements one by one {"Apple", "Banana", "Orange", "Grapes"}:
import java.util.List;
import java.util.Stack;
public class iterateOverList {
public static void main(String[] args) {
//instantiating a List using Stack class
List<String> fruits = new Stack<>();
//adding element to it
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
fruits.add("Grapes");
System.out.println("The list elements are: ");
//iterate over a vowels using for-each loop
for(String f : fruits){
System.out.println(f);
}
}
}
Following is the output of the above program:
The list elements are: Apple Banana Orange Grapes