Null safe Collection as Stream in Java 8

2017-01-11T19:47:58

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?

Copyright License:
Author:「Gondy」,Reproduced under the CC 4.0 BY-SA copyright license with link to original source & disclaimer.
Link to:https://stackoverflow.com/questions/41590134/null-safe-collection-as-stream-in-java-8

About “Null safe Collection as Stream in Java 8” questions

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 crea...
I wrote bellow code to check some condition. /** * Returns true if any of the dose detail is an x * @return boolean */ public &lt;DD extends BD&lt;DI&gt;, DI extends BI&gt; boolean Y(final Coll...
Is it recommended/good approach to check if a stream is not empty or not null before iterating What I can think of is assiging stream() to Stream vairable and check empty and null Is there any ja...
Are Java 8 Streams safe return types for public methods, in that it would be impossible to mutate the underlying object given a stream from it? For example, if I have a List and return list.stream...
Say I have a List of objects that being modified by only one thread (the thread can add or remove objects) and and another thread occasinally uses stream api from the above collecion to do some str...
I need to find out if there is any value present for the characteristsic object . right now i am iterating all the loops to get check if value is present or not . the code is also not null safe . b...
The collect operation in Java 8 Stream API is defined as a mutable reduction that can be safely executed in parallel, even if the resulting Collection is not thread safe. Can we say the same about...
I'm using this to get the newest item. How can I get this to be null safe and sort with null dates last (oldest). createDt is a joda LocalDate object. Optional&lt;Item&gt; latestItem = items.strea...
What's the best way to do null-safe contains on a Java collection? in other words - if (collection != null &amp;&amp; collection.contains(x)) ? I was hoping Apache commons-collections had
Last week got very strange NPE in a stream that caused my lots of troubles so right now I'm feeling like being over-safe with NPE when using a Stream. Here is my method right now: private boolean

Copyright License:Reproduced under the CC 4.0 BY-SA copyright license with link to original source & disclaimer.