List Iteration Methods in Java: Explanation & Practice
Different ways to iterate a list
Problem summary
Iterate through a list using for-each loop and print each element.
Starter code
import java.util.*;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(10, 20, 30, 40, 50);
// Print each number using for-each
}
}Expected output and test cases
- Print all numbers
10 20 30 40 50
Hints
- for (Type item : collection)
- Can also use traditional for loop
- Or use forEach with lambda
Related Collections exercises
Practice all Collections exercises · Run this idea in the Java compiler