Java stream return null

Can Stream.collect() Return the null Value?

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Читайте также:  Php md5 with key

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

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

We’re looking for a new Java technical editor to help review new articles for the site.

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 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 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 result = LANGUAGES.stream() .filter(s -> s != null && s.length() == 1) .collect(toList()); assertNotNull(result); assertTrue(result.isEmpty()); Map result2 = LANGUAGES.stream() .filter(s -> s != null && s.length() == 1) .collect(toMap(s -> s.charAt(0), Function.identity())); assertNotNull(result2); assertTrue(result2.isEmpty()); Map 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, ArrayList> 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 notNullResult = LANGUAGES.stream() .filter(Objects::isNull) .collect(emptyListToNullCollector); assertNotNull(notNullResult); assertEquals(Arrays.asList(null, null), notNullResult); List 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 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 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.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Источник

Оцените статью