The ArrayList forEach() method performs the specified Consumer action on 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. Internal Implementation of forEach()
As shown below, the method iterates over all list elements and calls action.accept()
for each element. Here the 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 Consumer action to be performed for each element.
- Method returns – void.
- Method throws – ConcurrentModificationException and NullPointerException.
2. ArrayList forEach() Examples
2.1. Print All List Items to the Console
Let us begin with a very simple Java program that just prints each of the elements from the List. We can apply the same code for ArrayList class as well.
List<String> list = Arrays.asList("A","B","C","D");
list.forEach(System.out::println);
2.2. Custom Consumer Actions
A Consumer implementation takes a single argument, and returns no value. We can also pass the custom actions we have created in other places.
For example, the following code iterates a list and prints the lowercase strings using the forEach() API.
Consumer<String> action = x -> System.out.println(x.toLowerCase());
list.forEach(action);
2.3. Lambda Expressions
We can pass the simple lambda expression inline, as well.
list.forEach(e -> System.out.println(e.toLowerCase()));
If there are more than one statement in the Consumer action then use the curly braces to wrap the statements.
list.forEach(e -> {
System.out.println(e.toLowerCase());
//other statements
});
Happy Learning !!
Read More: