Skip to content

How to best create a Java 8 stream from a nullable object?

What is the best/idiomatic way of doing a null check before getting a stream?

I have method that is receiving a List that might be null. So I can’t just call .stream() on the passed in value. Is there some static helper in that would give me an empty stream if a value is null?

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.