VOOZH about

URL: https://www.geeksforgeeks.org/java/arraylist-foreach-method-in-java/

⇱ ArrayList forEach() Method in Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

ArrayList forEach() Method in Java

Last Updated : 11 Jul, 2025

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.


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.


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.


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.

Comment