The forEach()
method is a modern and powerful way to iterate through an ArrayList
in Java. Introduced in Java 8 as part of the Iterable
interface, it allows you to perform a specified action on each element of the list using concise and readable lambda expressions or method references.
What Is the forEach() Method in ArrayList?
- The
forEach()
method takes a Consumer functional interface as an argument, representing an operation to be performed on each element of the list. - It sequentially applies this operation to every element in the
ArrayList
. - The method does not modify the list by itself (unless your action changes the elements explicitly).
- It does not return any value (
void
return type). - Unlike a traditional
for
or enhancedfor-each
loop,forEach()
leverages Java’s functional programming capabilities, enabling more expressive and compact code.
Syntax
public void forEach(Consumer<? super E> action)
Parameters
Parameter | Description |
---|---|
action | The operation to be performed on each element of the ArrayList . |
Return Value
- The
forEach()
method returns void — it performs the action but does not return a value.
Exceptions
- Throws
NullPointerException
if the specified action isnull
. - Any unchecked exceptions thrown by the action are propagated to the caller.
How Does forEach() Work Internally?
- The method accesses each element of the
ArrayList
in the order they are stored. - It calls the
accept()
method of the providedConsumer
for each element. - The iteration continues until all elements have been processed or an exception is thrown.
Examples of Using the forEach() Method
1. Print Each Element of an ArrayList
import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList<String> fruits = new ArrayList<>(); fruits.add("Apple"); fruits.add("Banana"); fruits.add("Orange"); // Using forEach with a lambda expression fruits.forEach(fruit -> System.out.println(fruit)); } }
Output:
Apple
Banana
Orange
2. Using Method Reference for Cleaner Code
import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList<String> fruits = new ArrayList<>(); fruits.add("Apple"); fruits.add("Banana"); fruits.add("Orange"); // Using method reference for cleaner // code to print each element fruits.forEach(System.out::println); } }
The output will be the same as the previous example, but this syntax is more concise and expressive.
3. Modify Elements Using forEach (with Caution)
Since forEach()
does not return values or change internal list structure by itself, modifying elements inside it requires careful handling. You can update elements using their index as shown:
import java.util.ArrayList; import java.util.concurrent.atomic.AtomicInteger; public class ModifyExample { public static void main(String[] args) { ArrayList<Integer> prices = new ArrayList<>(); prices.add(100); prices.add(200); prices.add(300); AtomicInteger index = new AtomicInteger(0); prices.forEach(price -> { int discounted = (int) (price * 0.9); prices.set(index.getAndIncrement(), discounted); }); System.out.println(prices); // Output: [90, 180, 270] } }
4. Performing Complex Operations Inside forEach
You can perform any valid action such as logging, calculations, or conditional processing inside the forEach lambda.
fruits.forEach(fruit -> { if (fruit.startsWith("A")) { System.out.println(fruit + " starts with A!"); } });
Important Notes
- The order of execution is the same as the list order (from index 0 to
size()-1
). forEach()
does not support modifying the structure of theArrayList
while iterating (like adding or removing elements), as this causesConcurrentModificationException
.- It is typically used for read-only operations or safe modifications (e.g., updating existing elements).
- To use
forEach()
, you need Java 8 or above.
Summary
Aspect | Details |
---|---|
Method Purpose | Perform an action on every element of the ArrayList |
Syntax | void forEach(Consumer<? super E> action) |
Parameters | A Consumer functional interface (typically a lambda or method reference) |
Return Type | void |
Exception | Throws NullPointerException if the action is null |
Java Version | Introduced in Java 8 |
Conclusion
The forEach()
method is a concise, expressive way to process elements in a Java ArrayList
. It leverages Java’s functional programming features to simplify iteration and avoid boilerplate code. Whether printing elements, performing calculations, or applying conditional logic, forEach()
is a versatile tool in your Java collection toolkit.