Null safe Collection as Stream in Java 8

JavaCollectionsNullJava 8Java Stream

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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 ())...

Solution 2 - Java

You can use org.apache.commons.collections4.CollectionUtils::emptyIfNull function:

import static org.apache.commons.collections4.CollectionUtils.emptyIfNull;
      
emptyIfNull(list).stream()
                 .filter(...);

Solution 3 - Java

Not sure if helps, but since Java 9, you can just write:

Stream.ofNullable(nullableCollection)
      .flatMap(Collection::stream)

Solution 4 - Java

Your collectionAsStream() method can be simplified to a version even simpler than when using Optional:

public static <T> Stream<T> collectionAsStream(Collection<T> collection) {
    return collection == null ? Stream.empty() : collection.stream();
}

Note that in most cases, it's probably better to just test for nullness before building the stream pipeline:

if (collection != null) {
    collection.stream().filter(...)
} // else do nothing

What you want seems to be only useful when you need to return the stream (including for flatmapping), or maybe concatenate it with another one.

Solution 5 - Java

You can use something like that:

public static void main(String [] args) {
    List<String> someList = new ArrayList<>();
    asStream(someList).forEach(System.out::println);
}

public static <T> Stream<T> asStream(final Collection<T> collection) {
    return Optional.ofNullable(collection)
            .map(Collection::stream)
            .orElseGet(Stream::empty);
}

Solution 6 - Java

If downloading the library org.apache.commons.collections4 is not an option, you can just write your own wrapper/convenience method.

public static <T> Stream<T> asStream(final Collection<T> collection) {
    return collection == null ? ( Stream<T> ) Collections.emptyList().stream() 
                              : collection.stream();
}

Or wrapping the collection with Optional.ofNullable

public static <T> Stream<T> asStream(final Collection<T> collection) {
    return Optional.ofNullable(collection)
            .orElse( Collections.emptySet()).stream();
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGondyView Question on Stackoverflow
Solution 1 - JavaEranView Answer on Stackoverflow
Solution 2 - JavagregView Answer on Stackoverflow
Solution 3 - JavafhiegelView Answer on Stackoverflow
Solution 4 - JavaDidier LView Answer on Stackoverflow
Solution 5 - Javag-tView Answer on Stackoverflow
Solution 6 - JavaalltejView Answer on Stackoverflow