1. Overview
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, check out our collection of articles.
A quick and practical overview of the difference between Collection.stream().forEach() and Collection.forEach().
Java Streams are often a good replacement for loops. Where loops provide the break keyword, we have do something a little different to stop a Stream.
The article is an example-heavy introduction of the possibilities and operations offered by the Java 8 Stream API.
2. Basics of forEach()
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.
3. Using the forEach() Method with Collections
The forEach() method aligns with the Java functional programming paradigm, making code more declarative.
3.1. Iterating Over a List
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.
3.2. Iterating Over a Map Using forEach()
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.
3.3. Iterating Over a Map by Iterating entrySet()
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()));
3.4. Using forEach() Method for Parallel Operation
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.
4. How Not to Use forEach()
Although the forEach() method is convenient, it has limitations.
4.1. Cannot Be Directly Invoked on Arrays
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.
4.2. Cannot Modify the Collection Itself
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.
4.3. Cannot Break or Continue a Loop
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.
4.4. Doesn’t Permit Counter
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.
4.5. Cannot Access Next or Previous Element
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.
5. forEach() vs. Traditional for Loop
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.
6. forEach() vs. Enhanced for Loop
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.
6.1. Internal Iterator – forEach()
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.
6.2. External Iterator – for-loop
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.
7. Conclusion
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 to perform an action on each element in the collection.
The code backing this article is available on GitHub. Once you're
logged in as a Baeldung Pro Member, start learning and coding on the project.