Skip to content

WebDevHubs

  • Home
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • Java
  • Selenium
  • PHP
  • Python
  • Programs
  • Toggle search form

Java ArrayList forEach() Method

Posted on July 22, 2025July 22, 2025 By Admin No Comments on Java ArrayList forEach() Method

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 enhanced for-each loop, forEach() leverages Java’s functional programming capabilities, enabling more expressive and compact code.

Syntax

public void forEach(Consumer<? super E> action)

Parameters

ParameterDescription
actionThe 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 is null.
  • 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 provided Consumer 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 the ArrayList while iterating (like adding or removing elements), as this causes ConcurrentModificationException.
  • 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

AspectDetails
Method PurposePerform an action on every element of the ArrayList
Syntaxvoid forEach(Consumer<? super E> action)
ParametersA Consumer functional interface (typically a lambda or method reference)
Return Typevoid
ExceptionThrows NullPointerException if the action is null
Java VersionIntroduced 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.

Java Tags:Java-ArrayList, Java-ArrayList-Method, Java-Collections

Post navigation

Previous Post: Java ArrayList ensureCapacity() Method
Next Post: Java ArrayList get() Method

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Java ArrayList
  • Java ArrayList Methods
  • Java ArrayList add() Method
  • Java ArrayList addAll() Method
  • Java ArrayList clear() Method
  • Java ArrayList clone() Method
  • Java ArrayList contains() Method
  • Java ArrayList ensureCapacity() Method
  • Java ArrayList forEach() Method
  • Java ArrayList get() Method
  • Java ArrayList indexOf() Method
  • Java ArrayList isEmpty() Method
  • Java ArrayList iterator() Method
  • Java ArrayList lastIndexOf() Method
  • Java ArrayList listIterator() Method

Recent Posts

  • Java ArrayList remove() Method
  • Java ArrayList listIterator() Method
  • Java ArrayList lastIndexOf() Method
  • Java ArrayList iterator() Method
  • Java ArrayList isEmpty() Method

Recent Comments

No comments to show.

Important Pages

  • About Us
  • Contact Us
  • Terms of Use
  • Privacy Policy

Web Development

  • HTML
  • CSS
  • JavaScript
  • PHP

Programming Languages

  • Java
  • Python
  • PHP
  • Programs

Others

  • Selenium
  • Lodash
  • Java ArrayList
  • JavaScript Array Methods

Copyright © 2025 WebDevHubs.

Powered by PressBook Green WordPress theme