Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null safe Collection as Stream in Java 8

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?

like image 393
Gondy Avatar asked Jan 11 '17 11:01

Gondy


People also ask

How do you handle null in stream?

We can use lambda expression str -> str!= null inside stream filter() to filter out null values from a 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

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 ())... 
like image 182
Eran Avatar answered Sep 19 '22 06:09

Eran