
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
Iterate a List Using For Loop in Java
To iterate over a List using a for loop, we need to know the size (which can be calculated using the size() method) of the list, so that the loop can execute an accessing element code block till the last position, which is starts from index 0.
Once the loop reaches at the last index of the list, it will stop executing and exit. Here are a few examples of how to iterate over a list using a for loop:
Iterate a List using For Loop
A for-loop is a "control flow statement " which is used to execute a block of code repeatedly. Once the condition will be false, it will stop executing.
The List can be iterate (loop through) using the control flow statement such as for-loop, which will help to access each element in the List.
Example 1
In the following example, we iterate over a List (instantiating using ArrayList class) using a for-loop to print each element one by one of the List {10, 20, 30, 40}:
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(10); list.add(20); list.add(30); list.add(40); System.out.println("The list elements are: "); //iterate over a list using for-loop for(int i= 0; i<list.size(); i++) { System.out.print(list.get(i) + " "); } } }
The above program produces the following output:
The list elements are: 10 20 30 40
Example 2
In the example below, we use the for-loop to iterate over a List (instantiating using Stack Class) to print each of its elements one by one {"A", "E", "I", "O", "U"}:
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> vowels = new Stack<>(); //adding element to it vowels.add("A"); vowels.add("E"); vowels.add("I"); vowels.add("O"); vowels.add("U"); System.out.println("The list elements are: "); //iterate over a vowels using for-loop for(int i= 0; i<vowels.size(); i++) { System.out.print(vowels.get(i) + " "); } } }
Following is the output of the above program:
The list elements are: A E I O U