I am looking for method that can make stream of collection, but is null safe. If collection is null, empty stream is returned. Like this:
Utils.nullSafeStream(collection).filter(...);
I have created my own method:
public static <T> Stream<T> nullSafeStream(Collection<T> collection) {
if (collection == null) {
return Stream.empty();
}
return collection.stream();
}
But I am curious, if there is something like this in standard JDK?
You can use something like that:
If downloading the library
org.apache.commons.collections4
is not an option, you can just write your own wrapper/convenience method.Or wrapping the collection with
Optional.ofNullable
You can use org.apache.commons.collections4.CollectionUtils::emptyIfNull function:
Not sure if helps, but since Java 9, you can just write:
You could use
Optional
:I chose
Collections.emptySet()
arbitrarily as the default value in casecollection
is null. This will result in thestream()
method call producing an emptyStream
ifcollection
is null.Example :
Output:
Alternately, as marstran suggested, you can use:
Your
collectionAsStream()
method can be simplified to a version even simpler than when usingOptional
:Note that in most cases, it's probably better to just test for nullness before building the stream pipeline:
What you want seems to be only useful when you need to return the stream (including for flatmapping), or maybe concatenate it with another one.