Course – LS – All

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

>> CHECK OUT THE COURSE

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.

As usual, all code snippets presented here are available over on GitHub.

Course – LS – All

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

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.