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 java 8 function/feature to check that?
ref :- https://www.baeldung.com/java-null-safe-streams-from-collections
No, it's not necessary¹.
As long as you use empty Streams instead of null (for example as method parameters), everything works just fine. You don't need to check if a Stream
is empty, just like you don't need to check if a Collection
is empty, if you use empty collections instead of nulls in your code (and you should).
¹ Now this is assuming "original" streams coming from a continuous source (collection, generator). You can easily create a null-containing Stream with something like map(o -> o.getPossiblyNull())
. In this case you may want to use .filter(Objects::nonNull)
to remove any null elements from the Stream.