ArrayList forEach() example – Java 8

ArrayList forEach() method performs the argument statement/action for each element of the list until all elements have been processed or the action throws an exception.

By default, actions are performed on elements taken in the order of iteration.

1. ArrayList forEach() method

As shown below, method simply iterate over all list elements and call action.accept() for each element. Here action is an instance of Consumer interface.

@Override
public void forEach(Consumer<? super E> action) 
{
    Objects.requireNonNull(action);

    final int expectedModCount = modCount;

    @SuppressWarnings("unchecked")
    final E[] elementData = (E[]) this.elementData;
    final int size = this.size;
    for (int i=0; modCount == expectedModCount && i < size; i++) {
        action.accept(elementData[i]);
    }
    if (modCount != expectedModCount) {
        throw new ConcurrentModificationException();
    }
}
  • Method parameter – The action to be performed for each element.
  • Method returns – void.
  • Method throws – ConcurrentModificationException and NullPointerException.

2. ArrayList forEach() example

Java program to iterate an arraylist using forEach() method. This example iterate a list and print the lowercase of strings in the list.

Notice how we are passing a lambda expression to the forEach() statement in second iteration.

import java.util.ArrayList;
import java.util.Arrays;

public class ArrayListExample 
{
    public static void main(String[] args) throws CloneNotSupportedException 
    {
       ArrayList<String> names = new ArrayList<>(Arrays.asList("A","B","C","D")); 
       
       //1 
       names.forEach(name -> System.out.println(name.toLowerCase()));

       //2
       Consumer<String> lambdaExpression = x -> System.out.println(x.toLowerCase());

       names.forEach(lambdaExpression);
    }
}

Program output.

a
b
c
d

a
b
c
d

Please note that we can pass a static method in forEach() statement if we want to have multiple statements to handle the list value.

import java.util.ArrayList;
import java.util.Arrays;

public class ArrayListExample 
{
    public static void main(String[] args) throws CloneNotSupportedException 
    {
        ArrayList<String> names = new ArrayList<>(Arrays.asList("A","B","C","D")); 
        
       names.forEach(name -> printString(name));
    }
    
    private static void printString(String str) {
        System.out.println(str.toLowerCase());
    }
}

Program output.

a
b
c
d

Happy Learning !!

Read More:

A Guide to Java ArrayList
ArrayList Java Docs

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.