Null safe Collection as Stream in Java 8

2020-02-07 17:21发布

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?

6条回答
Rolldiameter
2楼-- · 2020-02-07 17:22

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);
}
查看更多
做自己的国王
3楼-- · 2020-02-07 17:28

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();
}
查看更多
太酷不给撩
4楼-- · 2020-02-07 17:34

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

  org.apache.commons.collections4.CollectionUtils.emptyIfNull(list).stream().filter(...);
查看更多
等我变得足够好
5楼-- · 2020-02-07 17:34

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

Stream.ofNullable(nullableCollection)
      .flatMap(Collection::stream)
查看更多
乱世女痞
6楼-- · 2020-02-07 17:40

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 ())...
查看更多
手持菜刀,她持情操
7楼-- · 2020-02-07 17:43

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.

查看更多
登录 后发表回答