What is the best/idiomatic way of performing a null-check before generating a stream?
I have a method that receives a List
that might be null
. So I can’t just call stream()
on the value that is passed. Is there some static helper in that would give me an empty stream if a value is null?
Advertisement
Answer
I agree with Stuart Marks that list == null ? Stream.empty() : list.stream()
is the right way to do this (see his answer), or at least the right way to do this pre-Java 9 (see edit below), but I’ll leave this answer up to demonstrate usage of the Optional API.
<T> Stream<T> getStream(List<T> list) { return Optional.ofNullable(list).map(List::stream).orElseGet(Stream::empty); }
Edit: Java 9 added the static factory method Stream.<T>ofNullable(T)
, which returns the empty stream given a null
argument, otherwise a stream with the argument as its only element. If the argument is a collection, we can then flatMap
to turn it into a stream.
<T> Stream<T> fromNullableCollection(Collection<? extends T> collection) { return Stream.ofNullable(collection).flatMap(Collection::stream); }
This doesn’t misuse the Optional API as discussed by Stuart Marks, and in contrast to the ternary operator solution, there’s no opportunity for a null pointer exception (like if you weren’t paying attention and screwed up the order of the operands). It also works with an upper-bounded wildcard without needing SuppressWarnings("unchecked")
thanks to the signature of flatMap
, so you can get a Stream<T>
from a collection of elements of any subtype of T
.