In this section, we will learn what the Stream empty() method is and how to use it in Java.
What is Java Stream empty() Method?
The Java Stream empty() method is used to create an empty Stream object.
Note: we might need an empty stream when there’s a method that needs a stream as its argument to function correctly, but we only care about some other aspects of that method and don’t want to pass it an actual stream of elements.
So using this empty() method we can create an empty stream and pass that to such a method to avoid getting the NullPointerException.
Java empty() Method Syntax:
static <T> Stream<T> empty()
empty() Method Parameters:
The method does not take an argument.
empty() Method Return Value:
The return value of this method is a new stream object that does not have an element.
empty() Method Exceptions:
The method does not throw an exception.
Example: using Stream empty() method
import java.util.stream.Stream; class Main{ public static void main(String[] args) { Stream<Integer> stream = Stream.empty(); System.out.println(stream.count()); } }
Output:
0
As you can see, the result of calling this method returned an empty stream.