![]() |
VOOZH | about |
In Java, the ArrayList.forEach() method is used to iterate over each element of an ArrayList and perform certain operations for each element in ArrayList.
Example 1: Here, we will use the forEach() method to print all elements of an ArrayList of Strings.
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.
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 2: Here, we will use the forEach() method with a lambda expression to print the square of each element in an ArrayList of Integers.
4 9 16
Example 3: Here, we will use the forEach() method with a conditional statement to filter and print eligible elements of an ArrayList of Integers.
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.