ArrayList forEach() Method in Java
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.
// Java program to demonstrate the use of forEach()
// with an ArrayList of Strings
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 of ArrayList.forEach() Method
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.
Other Examples of forEach() Method
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.
// Java program to demonstrate
// custom actions using forEach()
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
Example 3: Here, we will use the forEach() method with a conditional statement to filter and print eligible elements of an ArrayList of Integers.
// Java program to demonstrate
// conditional actions using forEach()
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.