The forEach() method of the ArrayList class is used to iterate over each element of an ArrayList and perform a specified action on every element. Introduced in Java 8, it accepts a Consumer functional interface, making it easy to use lambda expressions and method references for concise and readable code.
- Simplifies iteration without using explicit loops.
- Introduced in Java 8 as part of the Collections Framework enhancements.
import java.util.ArrayList;
public class GFG {
public static void main(String[] args) {
// Create an ArrayList of Strings
ArrayList<String> s = new ArrayList<>();
s.add("Cherry");
s.add("Blueberry");
s.add("Strawberry");
// Use forEach() to print each fruit
s.forEach(System.out::println);
}
}
Output
Cherry Blueberry Strawberry
Explanation: In the above example, we use the forEach() method with a method reference (System.out::println) to print each element in the ArrayList.
Syntax
public void forEach(Consumer<? super E> action)
Parameter: action: A functional interface "Consumer" that specifies the action to be performed for each element in the ArrayList. It accepts a single parameter and does not return any value.
Exception: This method throws NullPointerException if the specified action is null.
Example: Using the forEach() method with a lambda expression to print the square of each element in an ArrayList of Integers.
import java.util.ArrayList;
public class GFG {
public static void main(String[] args) {
// Create an ArrayList of Integers
ArrayList<Integer> n = new ArrayList<>();
n.add(2);
n.add(3);
n.add(4);
// Use forEach() to print the
// square of each number
n.forEach(num -> System.out.println(num * num));
}
}
Output
4 9 16
Explanation: Here, an ArrayList<Integer> is created with the values 2, 3, and 4. The forEach() method uses a lambda expression to calculate and print the square of each number during iteration.
Example: Using the forEach() method with a conditional statement to filter and print eligible elements of an ArrayList of Integers.
import java.util.ArrayList;
public class GFG {
public static void main(String[] args) {
// Create an ArrayList of Integers
ArrayList<Integer> a = new ArrayList<>();
a.add(24);
a.add(18);
a.add(10);
// Use forEach() to print
// ages that are 18 or above
a.forEach(age -> {
if (age >= 18) {
System.out.println("Eligible age: " + age);
}
});
}
}
Output
Eligible age: 24 Eligible age: 18
Explanation: In the above example, we use the forEach() method with a lambda expression and conditional logic to filter and print elements based on a condition.
Difference Between forEach() and Enhanced for Loop
forEach() | Enhanced for Loop |
|---|---|
| Introduced in Java 8. | Available since Java 5. |
Uses a Consumer functional interface. | Uses the enhanced for syntax. |
| Supports lambda expressions and method references. | Does not support lambda expressions directly. |
| More concise for simple operations. | Better suited for complex iteration logic or when break/continue is required. |
Advantages of forEach() Method
- Makes iteration concise and readable.
- Eliminates the need for explicit loops.
- Supports functional programming with lambda expressions.
- Works seamlessly with method references.
- Reduces boilerplate code.
- Suitable for applying the same operation to every element.