In the other answers, the Optional instance is created and used strictly within the same statement. The Optional class is primarily useful for communicating with the caller about presence or absence of a return value, fused with the actual value if present. Using it wholly within a single method seems unnecessary.
Let me propose the following more prosaic technique:
static <T> Stream<T> nullableListToStream(List<T> list) {
return list == null ? Stream.empty() : list.stream();
}
I guess the ternary operator is somewhat déclassé these days, but I think this is the simplest and most efficient of the solutions.
If I were writing this for real (that is, for a real library, not just sample code on Stack Overflow) I'd put in wildcards so that that the stream return type can vary from the List type. Oh, and it can be a Collection, since that's where the stream() method is defined:
@SuppressWarnings("unchecked")
static <T> Stream<T> nullableCollectionToStream(Collection<? extends T> coll) {
return coll == null ? Stream.empty() : (Stream<T>)coll.stream();
}
(The warning suppression is necessary because of the cast from Stream<? extends T> to Stream<T> which is safe, but the compiler doesn't know that.)