可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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?
回答1:
You can use org.apache.commons.collections4.CollectionUtils::emptyIfNull function:
org.apache.commons.collections4.CollectionUtils.emptyIfNull(list).stream().filter(...);
回答2:
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 ())...
回答3:
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.
回答4:
Not sure if helps, but since Java 9, you can just write:
Stream.ofNullable(nullableCollection)
.flatMap(Collection::stream)
回答5:
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();
}
回答6:
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);
}