GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||||||
GeezerVison is showing www.geeksforgeeks.org — ArrayList forEach() Method in Java - GeeksforGeeks ArrayList forEach() Method in JavaLast Updated : 20 Jul, 2026 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.
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
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.
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.
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
Advantages of forEach() Method
Comment Explore | ||||||||||
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |