1. Introduction
Iterating over a List is a fundamental operation in Java, allowing developers to access and manipulate each element in the list. In this guide, we will explore different ways to iterate over a List in Java, including using enhanced for loop, iterator, and Java 8 forEach method.
2. Program Steps
1. Import the necessary libraries.
2. Create and initialize a List.
3. Use different methods to iterate over the list.
4. Output the elements of the list.
3. Code Program
// Step 1: Import the necessary library
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class ListIteration {
public static void main(String[] args) {
// Step 2: Create and initialize a List
List<String> fruitList = Arrays.asList("Apple", "Banana", "Cherry", "Date");
// Step 3: Use different methods to iterate over the list
// Using enhanced for loop
System.out.println("Using enhanced for loop:");
for (String fruit : fruitList) {
System.out.println(fruit);
}
// Using iterator
System.out.println("Using iterator:");
Iterator<String> iterator = fruitList.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
// Using forEach method with lambda expression
System.out.println("Using forEach with lambda:");
fruitList.forEach(fruit -> System.out.println(fruit));
}
}
Output:
Using enhanced for loop: Apple Banana Cherry Date Using iterator: Apple Banana Cherry Date Using forEach with lambda: Apple Banana Cherry Date
4. Step By Step Explanation
Step 1: Start by importing the necessary libraries. For this program, we are using List, Arrays, and Iterator.
Step 2: Create and initialize a List with some elements.
Step 3: We use three different methods to iterate over the list.
– Firstly, we use an enhanced for loop, a concise way to traverse each element.
– Secondly, we use an Iterator which provides a way of accessing the elements of an aggregate object sequentially without exposing its underlying representation.
– Lastly, we use the forEach method with a lambda expression, introduced in Java 8, which offers a concise and functional approach for iterating elements.
Step 4: In each iteration method, print out the elements of the list.