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 – 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 – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

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

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

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

1. Overview

One significant new feature that Java 8 introduced is the Stream API. Further, it ships with a set of Collectors that allow us to call the Stream.collect() method to collect elements in a stream into the desired collections, such as List, Set, Map, and so on.

In this tutorial, we’ll discuss whether the collect() method can return a null value.

2. Introduction to the Problem

The question, “Can Stream‘s collect() method return null?” has two meanings:

  • Must we perform the null check when we use this method with standard collectors?
  • Is it possible to make the collect() method return null if we really want to?

Our discussion in this tutorial will cover both perspectives.

First, let’s create a list of strings as the input data for easier demonstration later:

final List<String> LANGUAGES = Arrays.asList("Kotlin", null, null, "Java", "Python", "Rust");

As we can see, the list LANGUAGES carries six string elements. It’s worth mentioning that two elements in the list are null values.

Later, we’ll build streams using this list as the input. Also, for simplicity, we’ll use unit test assertions to verify if the collect() method calls return null values.

3. The Collectors Shipped With the Standard Library Won’t Return null

We know that the Java Stream API has introduced a set of standard collectors. First, let’s take a look at whether the standard collectors can return null.

3.1. null Elements Won’t Make the collect() Method Return null

If a stream contains null elements, they will be included in the result of the collect() operation as null values, rather than causing the collect() method to return null itself. Let’s write a small test to verify it:

List<String> result = LANGUAGES.stream()
  .filter(Objects::isNull)
  .collect(toList());
assertNotNull(result);
assertEquals(Arrays.asList(null, null), result);

As the test above shows, first, we use the filter() method to get only null elements. Then, we collect the filtered null values in a List. It turns out that the two null elements are successfully collected in the result list. Therefore, null elements in the stream won’t cause the collect() method to return null.

3.2. An Empty Stream Won’t Make the collect() Method Return null

When we use the standard collectors, the collect() method of the Java Stream API will not return null even if the stream is empty.

Suppose the stream to be collected is empty. In that case, the collect() method will return an empty result container, such as an empty List, an empty Map, or an empty array, depending on the collector used in the collect() method.

Next, let’s take three commonly used collectors to verify this:

List<String> result = LANGUAGES.stream()
  .filter(s -> s != null && s.length() == 1)
  .collect(toList());
assertNotNull(result);
assertTrue(result.isEmpty());

Map<Character, String> result2 = LANGUAGES.stream()
  .filter(s -> s != null && s.length() == 1)
  .collect(toMap(s -> s.charAt(0), Function.identity()));
assertNotNull(result2);
assertTrue(result2.isEmpty());

Map<Character, List<String>> result3 = LANGUAGES.stream()
  .filter(s -> s != null && s.length() == 1)
  .collect(groupingBy(s -> s.charAt(0)));
assertNotNull(result3);
assertTrue(result3.isEmpty());

In the tests above, the filter(s -> s != null && s.length() == 1) method will return an empty stream as no element matches the condition. Then, as we can see, the toList(), toMap(), and groupingBy() collectors don’t return null. Instead, they produce an empty list or map as their result.

So, all standard collectors won’t return null.

4. Is It Possible to Make the Stream.collect() Method Return null?

We’ve learned that the standard collectors won’t make the collect() method return null. So now, let’s move to the question, what if we would like the Stream.collect() method to return null? Is it possible? The short answer is: yes.

So next, let’s see how to do that.

4.1. Creating a Custom Collector

The standard collectors don’t return null. Therefore, the Stream.collect() method won’t return null, either. However, if we can create our own collector that returns nullable results, Stream.collect() may return null, too.

Stream API has provided the static Collector.of() method that allows us to create a custom collector. The Collector.of() method takes four arguments:

  • A Supplier function – Return a mutable result container for the collect operation.
  • An accumulator function – Modify the mutable container to incorporate the current element.
  • A combiner function – Merge the intermediate results into a single final result container when the stream is processed in parallel.
  • An optional finisher function – Take the mutable result container and perform the required final transformations on it before returning the final result of the collect operation.

We should note that the last argument, the finisher function, is optional. This is because many collectors can simply use the mutable container as the final result. However, we can make use of this finisher function to ask the collector to return a nullable container.

Next, let’s create a custom collector called emptyListToNullCollector. As the name implies, we want the collector to work pretty much the same as the standard toList() collector, except that when the result list is empty, the collector will return null instead of an empty list:

Collector<String, ArrayList<String>, ArrayList<String>> emptyListToNullCollector = Collector.of(ArrayList::new, ArrayList::add, (a, b) -> {
    a.addAll(b);
    return a;
}, a -> a.isEmpty() ? null : a);

Now, let’s test our emptyListToNullCollector collector with the LANGUAGES input:

List<String> notNullResult = LANGUAGES.stream()
  .filter(Objects::isNull)
  .collect(emptyListToNullCollector);
assertNotNull(notNullResult);
assertEquals(Arrays.asList(null, null), notNullResult);

List<String> nullResult = LANGUAGES.stream()
  .filter(s -> s != null && s.length() == 1)
  .collect(emptyListToNullCollector);
assertNull(nullResult);

As we’ve seen in the test above, when the stream isn’t empty, our emptyListToNullCollector works as same as the standard toList() collector. But if the stream is empty, it returns null instead of an empty list.

4.2. Using the collectingAndThen() Method

Java Stream API has provided the collectingAndThen() method. This method allows us to apply a finishing function to the result of a collector. It takes two arguments:

  • A collector object – for example, the standard toList()
  • A finishing function – Take the result of the collect operation and perform any final transformations on it before returning the result of the stream operation

For example, we can use the collectingAndThen() function to make the returned list unmodifiable:

List<String> notNullResult = LANGUAGES.stream()
  .filter(Objects::nonNull)
  .collect(collectingAndThen(toList(), Collections::unmodifiableList));
assertNotNull(notNullResult);
assertEquals(Arrays.asList("Kotlin", "Java", "Python", "Rust"), notNullResult);
                                                                                   
//the result list becomes immutable
assertThrows(UnsupportedOperationException.class, () -> notNullResult.add("Oops"));

We’ve just learned how to create a custom collector using Collector.of(). This way allows us to implement the collecting logic freely. Further, we know that if the finisher function argument returns null, the Stream.collect(ourCustomCollector) can return null as well.

If we want to merely extend a standard collector by adding a finisher function, we can also use the collectingAndThen() method. It’s more straightforward than creating a custom collector.

So next, let’s use the collectingAndThen() method to achieve emptyListToNullCollector‘s functionalities:

List<String> nullResult = LANGUAGES.stream()
  .filter(s -> s != null && s.length() == 1)
  .collect(collectingAndThen(toList(), strings -> strings.isEmpty() ? null : strings));
assertNull(nullResult);

By using the collectingAndThen() method with a finisher function, we can see that the Stream.collect() method returns null when the stream is empty.

4.3. A Word About Nullable Collector

We’ve seen two approaches to make a collector return null, so that Stream.collect() returns null as well. However, we may want to think twice about whether we must make a collector nullable.

In general, it is considered good practice to avoid using nullable collectors unless there is a good reason for doing so. This is because null values can introduce unexpected manners and make it harder to reason about the code’s behavior. If a nullable collector is used, it is important to ensure that it’s used consistently and that any downstream processing can handle null values appropriately.

Because of that, all standard collectors don’t return null.

5. Conclusion

In this article, we discussed whether Stream.collect() can return null.

We’ve learned that all standard collectors won’t return null. Further, if it’s required, we can make Stream.collect() return null using Collector.of() or collectingAndThen(). However, in general, we should avoid using nullable collectors unless we have to do so.

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.

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.

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)