
Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:
Once the early-adopter seats are all used, the price will go up and stay at $33/year.
Introduced in Java 8, the forEach() method provides programmers with a concise way to iterate over a collection.
In this tutorial, we’ll see how to use the forEach() method with collections, what kind of argument it takes, and how this loop differs from the enhanced for-loop.
If you need to brush up on some Java 8 concepts, our collection of articles can help.
In Java, the Collection interface has Iterable as its super interface. This interface has a new API starting with Java 8:
void forEach(Consumer<? super T> action)
Simply put, the Javadoc of forEach states that it “performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception.”
And so, with forEach(), we can iterate over a collection and perform a given action on each element.
For instance, let’s consider an enhanced for-loop version of iterating and printing a Collection of Strings:
List names = List.of("Larry", "Steve", "James", "Conan", "Ellen");
for (String name : names) {
LOG.info(name);
}
We can write this using forEach():
names.forEach(name -> {
LOG.info(name);
});
Here, we invoke the forEach() on the collection and log the names to the console.
The forEach() method aligns with the Java functional programming paradigm, making code more declarative.
The forEach() method can be used on lists:
List names = List.of("Larry", "Steve", "James", "Conan", "Ellen");
names.forEach(name -> logger.info(name));
The code above logs all elements of the collection to the console.
Maps are not Iterable, but they do provide their own variant of forEach() that accepts a BiConsumer.
Java 8 introduces a BiConsumer instead of Consumer in Map‘s forEach() so that an action can be performed on both the key and value of a Map simultaneously.
Let’s create a Map with these entries:
Map<Integer, String> namesMap = new HashMap<>();
namesMap.put(1, "Larry");
namesMap.put(2, "Steve");
namesMap.put(3, "James");
Next, let’s iterate over namesMap using Map’s forEach():
namesMap.forEach((key, value) -> LOG.info(key + " " + value));
As we can see here, we’ve used a BiConsumer to iterate over the entries of the Map.
We can also iterate the EntrySet of a Map using Iterable’s forEach().
Since the entries of a Map are stored in a Set called EntrySet, we can iterate that using a forEach():
namesMap.entrySet().forEach(entry -> LOG.info(entry.getKey() + " " + entry.getValue()));
For large collections, using forEach() with a parallel stream can improve performance by utilizing multiple CPU cores:
List names = List.of("Larry", "Steve", "James", "Conan", "Ellen");
names.parallelStream().forEach(LOG::info);
The code above runs in parallel. However, parallel execution may increase resource consumption.
Although the forEach() method is convenient, it has limitations.
We can’t directly invoke the method on an array:
String[] foodItems = {"rice", "beans", "egg"};
foodItems.forEach(food -> logger.info(food));
The code above fails to compile because arrays don’t have the forEach() method. However, we can make it compile by converting the array to a stream:
Arrays.stream(foodItems).forEach(food -> logger.info(food));
Since stream has the forEach() method, we can convert an array into a stream and iterate over its element.
Moreover, we can’t modify the collection itself using the method:
List<String> names = List.of("Larry", "Steve", "James", "Conan", "Ellen");
names.forEach(name -> {
if (name.equals("Larry")) {
names.remove(name);
}
});
The code above throws a ConcurrentModificationException error because modifying collections while iterating over it with forEach() is not allowed. Unlike the traditional for loop, which allows modification with careful indexing.
Unlike traditional for loop, forEach() doesn’t support break or continue:
List<String> names = List.of("Larry", "Steve", "James", "Conan", "Ellen");
names.forEach(name -> {
if (name.equals("Steve")) {
break;
}
logger.info(name);
});
The code above throws an exception.
The forEach() method doesn’t support modifying a counter variable during iteration:
List<String> names = List.of("Larry", "Steve", "James", "Conan", "Ellen");
int count = 0;
names.forEach(name -> {
count++;
});
The code above results in a compilation error because lambda expression requires variables used inside them to be final, meaning their value can’t be modified after initialization.
However, we can use an atomic variable instead, which allows modification inside a lambda expression.
Furthermore, we can reference the previous or next element of a collection using the traditional for loop:
List<String> names = List.of("Larry", "Steve", "James", "Conan", "Ellen");
for (int i = 0; i < names.size(); i++) {
String current = names.get(i);
String previous = (i > 0) ? names.get(i - 1) : "None";
String next = (i < names.size() - 1) ? names.get(i + 1) : "None";
LOG.info("Current: {}, Previous: {}, Next: {}", current, previous, next);
}
In the code above, we use the index i to determine the previous (i – 1) and next (i + 1) elements.
However, this isn’t possible with the forEach() method because it processes elements individually without exposing their index.
Both can iterate over collections and arrays. However, the forEach() method isn’t as flexible as the traditional for loop.
The for loop allows us to explicitly define the loop control variables, conditions, and increments, while the forEach() method abstracts these details:
List names = List.of("Larry", "Steve", "James", "Conan", "Ellen");
for (int i = 0; i < names.size(); i++) {
LOG.info(names.get(i));
}
Also, we can modify the loop conditions:
for (int i = 0; i < names.size() - 1; i++) {
LOG.info(names.get(i));
}
In the code above, we skip the last element in the collection by modifying the loop condition – names.size() – 1. This level of flexibility isn’t possible with the forEach() method.
The forEach() method allows us to perform operations on the collection element and doesn’t permit modification to the collection itself.
The for loop allows us to perform operations on individual elements of a collection and permits us to modify the collection itself.
From a simple point of view, both loops provide the same functionality: loop through elements in a collection.
The main difference between them is that they are different iterators. The enhanced for-loop is an external iterator, whereas the new forEach method is internal.
This type of iterator manages the iteration in the background and leaves the programmer to just code what is meant to be done with the elements of the collection.
The iterator instead manages the iteration and makes sure to process the elements one by one.
Let’s see an example of an internal iterator:
List<String> names = List.of("Larry", "Steve", "James", "Conan", "Ellen");
names.forEach(name -> LOG.info(name));
In the forEach method above, we can see that the argument provided is a lambda expression. This means that the method only needs to know what is to be done, and all the work of iterating will be taken care of internally.
External iterators mix what and how the loop is to be done.
Enumerations, Iterators, and enhanced for-loop are all external iterators (remember the methods iterator(), next(), or hasNext()?). In all these iterators, it’s our job to specify how to perform iterations.
Consider this familiar loop:
List<String> names = List.of("Larry", "Steve", "James", "Conan", "Ellen");
for (String name : names) {
LOG.info(name);
}
Although we are not explicitly invoking hasNext() or next() methods while iterating over the list, the underlying code that makes this iteration work uses these methods. This implies that the complexity of these operations is hidden from the programmer, but it still exists.
Contrary to an internal iterator in which the collection does the iteration itself, here we require external code that takes every element out of the collection.
In this article, we showed that the forEach loop is more convenient than the normal for-loop.
We also saw how the forEach method works and what kind of implementation can be received as an argument in order to perform an action on each element in the collection.