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.nullSafeStrea
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();
}
Not sure if helps, but since Java 9, you can just write:
Stream.ofNullable(nullableCollection)
.flatMap(Collection::stream)
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 ())...
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);
}
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.
You can use org.apache.commons.collections4.CollectionUtils::emptyIfNull function:
org.apache.commons.collections4.CollectionUtils.emptyIfNull(list).stream().filter(...);