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?
We can use lambda expression str -> str!= null inside stream filter() to filter out null values from a stream.
I think this part of the documentation says that it cannot be null: Returns a Collector that accumulates the input elements into a new List. Highlights added by me. I think this new List means that something that isn't null.
You could use Optional
:
Optional.ofNullable(collection).orElse(Collections.emptySet()).stream()...
I chose Collections.emptySet()
arbitrarily as the default value in case collection
is null. This will result in the stream()
method call producing an empty Stream
if collection
is null.
Example :
Collection<Integer> collection = Arrays.asList (1,2,3); System.out.println (Optional.ofNullable(collection).orElse(Collections.emptySet()).stream().count ()); collection = null; System.out.println (Optional.ofNullable(collection).orElse(Collections.emptySet()).stream().count ());
Output:
3 0
Alternately, as marstran suggested, you can use:
Optional.ofNullable(collection).map(Collection::stream).orElse(Stream.empty ())...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With