Null safe Collection as Stream in Java 8

后端 未结 6 1467
天涯浪人
天涯浪人 2020-12-13 02:01

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         


        
6条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-13 02:34

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

    public static  Stream collectionAsStream(Collection 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.

提交回复
热议问题