Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 825
checketts Avatar asked Apr 02 '15 06:04

checketts


People also ask

How does Java handle null values in stream?

Java 8 Example: Filter null values from a stream We can use lambda expression str -> str!= null inside stream filter() to filter out null values from a stream.

Can a stream contain null?

Designers of the API did not want to assume whether null means the value is not present (absent value) or is present but equals null. Also, you can still use map(Optional::isNullable) on any stream.

Can Java stream return null?

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.


1 Answers

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.

like image 91
gdejohn Avatar answered Sep 29 '22 09:09

gdejohn