

That is, elements of a set cannot be duplicate. 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.A set is a collection of unique data. Next, let's create a custom collector called emptyListToNullCollector.

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

The standard collectors don't return null. So, all standard collectors won't return null. Instead, they produce an empty list or map as their result. Then, as we can see, the toList(), toMap(), and groupingBy() collectors don't return null. In the tests above, the filter(s -> s != null & s.length() = 1) method will return an empty stream as no element matches the condition. collect(toMap(s -> s.charAt(0), Function.identity())) Next, let's take three commonly used collectors to verify this: List result = LANGUAGES.stream() 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. Suppose the stream to be collected is empty. When we use the standard collectors, the collect() method of the Java Stream API will not return null even if the stream is empty.
