Course – Black Friday 2025 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our Black Friday Sale. All Access and Pro are 33% off until 2nd December, 2025:

>> EXPLORE ACCESS NOW

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 – 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

Partner – Orkes – NPI EA (cat=Java)
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.

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 – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Black Friday 2025 – NPI (cat=Baeldung)
announcement - icon

Yes, we're now running our Black Friday Sale. All Access and Pro are 33% off until 2nd December, 2025:

>> EXPLORE ACCESS NOW

1. Overview

In Java programming, working with collections and streams is a common task, especially in modern, functional programming paradigms. Java 8 introduced the Stream API, which provides powerful tools for processing data collections.

Two essential Collectors in the Stream API are Collectors.toMap() and Collectors.groupingBy(), both of which serve distinct purposes when it comes to transforming Stream elements into a Map.

In this tutorial, we’ll delve into the differences between these Collectorand explore scenarios where each is more appropriate.

2. The City Example

Examples can help us illustrate the problem. So, let’s create a simple immutable POJO class:

class City {
 
    private final String name;
    private final String country;
 
    public City(String name, String country) {
        this.name = name;
        this.country = country;
    }

   // ... getters, equals(), and hashCode() methods are omitted
}

As the code above shows, the City class only has two properties: the city name and the country in which the City is located.

Since we’ll be using Collectors.toMap() and Collectors.groupingBy() as the terminal Stream operations in our examples, let’s create some City objects to feed a Stream:

static final City PARIS = new City("Paris", "France");
static final City BERLIN = new City("Berlin", "Germany");
static final City TOKYO = new City("Tokyo", "Japan");

Now, we can create a Stream easily from these City instances:

Stream.of(PARIS, BERLIN, TOKYO);

Next, we’ll use Collectors.toMap() and Collectors.groupingBy() to convert a Stream of City instances to a Map and discuss the differences between these two Collectors.

For simplicity, we’ll use “toMap()” and “groupingBy()” to reference the two Collectors in the tutorial and employ unit test assertions to verify whether a transformation yields the expected result.

3. Taking City.country as the Key

First, let’s explore the basic usages of the toMap() and groupingBy() Collectors. We’ll use these two Collectors to transform a Stream. In the transformed Map result, we’ll take each City.country as the key.

Also, the key can be null. So, let’s create a City with null as its country:

static final City COUNTRY_NULL = new City("Unknown", null);

3.1. Using the toMap() Collector

toMap() allows us to define how keys and values are mapped from elements in the input Stream. We can pass keyMapper and valueMapper parameters to the toMap() method. Both parameters are functions, providing the key and the value in the result Map.

If we want the City instance itself to be the value in the result, and to get a Map<String, City>, we can use Function.identity() as the valueMapper:

Map<String, City> result = Stream.of(PARIS, BERLIN, TOKYO)
  .collect(Collectors.toMap(City::getCountry, Function.identity()));
 
Map<String, City> expected = Map.of(
  "France", PARIS,
  "Germany", BERLIN,
  "Japan", TOKYO
);
 
assertEquals(expected, result);

Also, toMap() works as expected even if the keyMapper function returns null:

Map<String, City> result = Stream.of(PARIS, COUNTRY_NULL)
  .collect(Collectors.toMap(City::getCountry, Function.identity()));
 
Map<String, City> expected = new HashMap<>() {{
    put("France", PARIS);
    put(null, COUNTRY_NULL);
}};
 
assertEquals(expected, result);

3.2. Using the groupingBy() Collector

The groupingBy() Collector is good at segregating Stream elements into groups based on a specified classifier function. Therefore, the value type in the result Map is a Collection. By default, it’s a List.

So next, let’s group our Stream by City.country:

Map<String, List<City>> result = Stream.of(PARIS, BERLIN, TOKYO)
  .collect(Collectors.groupingBy(City::getCountry));
 
Map<String, List<City>> expected = Map.of(
  "France", List.of(PARIS),
  "Germany", List.of(BERLIN),
  "Japan", List.of(TOKYO)
);
 
assertEquals(expected, result);

Unlike toMap(), groupingBy() cannot handle null as the classifier:

assertThrows(NullPointerException.class, () -> Stream.of(PARIS, COUNTRY_NULL)
  .collect(Collectors.groupingBy(City::getCountry)));

As the example shows, when the classifier function returns null, it throws a NullPointerException.

We’ve explored the two Collectors’ fundamental usages through examples. However, in our Stream, there are no duplicate countries among the City instances. In real-world projects, handling key collisions can be a common scenario we need to address.

So next, let’s see how the two Collectors deal with duplicate keys.

4. When There Are Duplicate Keys

Let’s create three additional cities:

static final City NICE = new City("Nice", "France");
static final City AACHEN = new City("Aachen", "Germany");
static final City HAMBURG = new City("Hamburg", "Germany");

Alongside the previously generated City instances, we now have cities with duplicate countries. For example, BERLIN, HAMBURG, and AACHEN have the same country: “Germany“.

Next, let’s explore how the toMap() and groupingBy() Collectors handle duplicate keys.

4.1. Using the toMap() Collector

If we continue with the previous approach, only passing the keyMapper and valueMapper to the toMap() Collector, an IllegalStateException will be thrown due to the presence of duplicate keys:

assertThrows(IllegalStateException.class, () -> Stream.of(PARIS, BERLIN, TOKYO, NICE, HAMBURG, AACHEN)
    .collect(Collectors.toMap(City::getCountry, Function.identity())));

When duplicate keys may occur, it’s necessary to provide a mergeFunction as the third parameter to toMap() to resolve collisions between values associated with the same key.

Next, let’s provide a lambda expression as the mergeFunction to toMap(), which selects the “smaller” City by comparing two city names lexicographically when their countries are the same:

Map<String, City> result = Stream.of(PARIS, BERLIN, TOKYO, NICE, HAMBURG, AACHEN)
  .collect(Collectors.toMap(City::getCountry, Function.identity(), (c1, c2) -> c1.getName()
     .compareTo(c2.getName()) < 0 ? c1 : c2));
 
Map<String, City> expected = Map.of(
  "France", NICE, // <-- from Paris and Nice
  "Germany", AACHEN, // <-- from Berlin, Hamburg, and Aachen
  "Japan", TOKYO
);
 
assertEquals(expected, result);

As the above example shows, the mergeFunction returns one City instance based on the given rule. Therefore, we still obtain a Map<String, City> as the result after calling the collect() method.

4.2. Using the groupingBy() Collector

On the other hand, since groupingBy() groups Stream elements into a Collection using the classifier, the previous code still works although the cities in the input Stream have the same country values:

Map<String, List<City>> result = Stream.of(PARIS, BERLIN, TOKYO, NICE, HAMBURG, AACHEN)
  .collect(Collectors.groupingBy(City::getCountry));
 
Map<String, List<City>> expected = Map.of(
  "France", List.of(PARIS, NICE),
  "Germany", List.of(BERLIN, HAMBURG, AACHEN),
  "Japan", List.of(TOKYO)
);
 
assertEquals(expected, result);

As we can see, cities with the same country names are grouped into the same List, as evidenced by the “France” and “Germany” entries in the result.

5. With Value Mappers

Up to this point, we’ve used the toMap() and groupingBy() Collectors to obtain associations of country -> City or country -> a Collection of City instances.

However, at times, we might need to map the Stream elements to different values. For example, we may wish to obtain associations of country -> City.name or country -> a Collection of City.name values.

Further, it’s important to note that the mapped values can be null. So, we may need to address the cases where the value is null. Let’s create a City whose name is null:

static final City FRANCE_NULL = new City(null, "France");

Next, let’s explore how to apply a value mapper to the toMap() and groupingBy() Collectors.

5.1. Using the toMap() Collector

As we’ve mentioned earlier, we can pass a valueMapper function to the toMap() method as the second parameter, allowing us to map the objects in the input Stream to different values:

Map<String, String> result = Stream.of(PARIS, BERLIN, TOKYO)
  .collect(Collectors.toMap(City::getCountry, City::getName));
 
Map<String, String> expected = Map.of(
  "France", "Paris",
  "Germany", "Berlin",
  "Japan", "Tokyo"
);
 
assertEquals(expected, result);

In this example, we use the method referenceCity::getName as the valueMapper parameter, mapping a City to its name.

However, toMap() encounters issues when the mapped values contain null:

assertThrows(NullPointerException.class, () -> Stream.of(PARIS, FRANCE_NULL)
  .collect(Collectors.toMap(City::getCountry, City::getName)));

As we can see, if the mapped values contain a null, toMap() throws a NullPointerException.

5.2. Using the groupingBy() Collector

Unlike toMap(), groupingBy() doesn’t directly support a valueMapper function as its parameter. However, we can supply another Collector as the second parameter to groupingBy(), allowing us to perform downstream reduction operations. For example, we can use the mapping() Collector to map grouped City instances to their names:

Map<String, List<String>> result = Stream.of(PARIS, BERLIN, TOKYO)
  .collect(Collectors.groupingBy(City::getCountry, mapping(City::getName, toList())));
 
Map<String, List<String>> expected = Map.of(
  "France", List.of("Paris"),
  "Germany", List.of("Berlin"),
  "Japan", List.of("Tokyo")
);
  
assertEquals(expected, result);

Furthermore, the combination of groupingBy() and mapping() can seamlessly handle null values:

Map<String, List<String>> resultWithNull = Stream.of(PARIS, BERLIN, TOKYO, FRANCE_NULL)
  .collect(Collectors.groupingBy(City::getCountry, mapping(City::getName, toList())));
 
Map<String, List<String>> expectedWithNull = Map.of(
  "France", newArrayList("Paris", null),
  "Germany", newArrayList("Berlin"),
  "Japan", List.of("Tokyo")
);
 
assertEquals(expectedWithNull, resultWithNull);

6. Conclusion

As we’ve seen in this article, Collectors.toMap() and Collectors.groupingBy() are powerful Collectors, each serving distinct purposes.

toMap() is suitable for transforming a Stream into a Map directly, while groupingBy() is good at categorizing Stream elements into groups based on certain criteria. 

Additionally, toMap() works although the keyMapper function returns null. But, groupingBy() throws a NullPointerException  if the classifier function returns null.

Since toMap() supports a valueMapper parameter, it’s pretty convenient to map values to a desired type. However, it’s important to note that if the valueMapper function returns null, toMap() throws a NullPointerException. In contrast, groupingBy() relies on other Collectors to map the Stream elements to a different type, and it effectively handles null values.

By understanding their differences and use cases, we can effectively use these Collectors in our Java applications to manipulate and process data streams.

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.
Course – Black Friday 2025 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our Black Friday Sale. All Access and Pro are 33% off until 2nd December, 2025:

>> EXPLORE ACCESS NOW

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

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Black Friday 2025 – NPI (All)
announcement - icon

Yes, we're now running our Black Friday Sale. All Access and Pro are 33% off until 2nd December, 2025:

>> EXPLORE ACCESS NOW

eBook – Java Streams – NPI (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 – 3 (cat = Jackson)