Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

Partner – Microsoft – NPI EA (cat = Baeldung)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

Partner – Microsoft – NPI EA (cat= Spring Boot)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, you can get started over on the documentation page.

And, you can also ask questions and leave feedback on the Azure Container Apps GitHub page.

Partner – Orkes – NPI EA (cat=Spring)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag=Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – All Access – NPI EA (cat= Spring)
announcement - icon

All Access is finally out, with all of my Spring courses. Learn JUnit is out as well, and Learn Maven is coming fast. And, of course, quite a bit more affordable. Finally.

>> GET THE COURSE
Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – LambdaTest – NPI EA (cat=Testing)
announcement - icon

End-to-end testing is a very useful method to make sure that your application works as intended. This highlights issues in the overall functionality of the software, that the unit and integration test stages may miss.

Playwright is an easy-to-use, but powerful tool that automates end-to-end testing, and supports all modern browsers and platforms.

When coupled with LambdaTest (an AI-powered cloud-based test execution platform) it can be further scaled to run the Playwright scripts in parallel across 3000+ browser and device combinations:

>> Automated End-to-End Testing With Playwright

Course – Spring Sale 2025 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our Spring Sale. All Courses are 25% off until 26th May, 2025:

>> EXPLORE ACCESS NOW

Course – Spring Sale 2025 – NPI (cat=Baeldung)
announcement - icon

Yes, we're now running our Spring Sale. All Courses are 25% off until 26th May, 2025:

>> EXPLORE ACCESS NOW

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, our collection of articles can help.

Further reading:

The Difference Between Collection.stream().forEach() and Collection.forEach()

A quick and practical overview of the difference between Collection.stream().forEach() and Collection.forEach().

How to Break from Java Stream 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 Java Stream API Tutorial

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 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 in order 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.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

Partner – Microsoft – NPI EA (cat = Spring Boot)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

Partner – Orkes – NPI EA (cat = Spring)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag = Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Course – Spring Sale 2025 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our Spring Sale. All Courses are 25% off until 26th May, 2025:

>> EXPLORE ACCESS NOW

Course – Spring Sale 2025 – NPI (All)
announcement - icon

Yes, we're now running our Spring Sale. All Courses are 25% off until 26th May, 2025:

>> EXPLORE ACCESS NOW

eBook Jackson – NPI EA – 3 (cat = Jackson)