Stream ofNullable(T) method in Java with examples
The ofNullable(T) method returns a sequential Stream containing a single element if this stream is non-null otherwise method returns an empty Stream. It helps to handle the null stream and NullPointerException.
Syntax:
static <T> Stream<T> ofNullable(T t)
Parameters: This method accepts a single parameter t which is the single element of which the Stream is to be returned.
Return value: This method returns a stream with a single element if the specified element is non-null, otherwise an empty stream.
Below programs illustrate ofNullable(T) method:
Program 1:
import java.util.stream.Stream;
public class GFG {
public static void main(String[] args)
{
Stream<String> value
= Stream.ofNullable( null );
System.out.println( "Values of Stream:" );
value.forEach(System.out::println);
}
}
|
The output printed on console of IDE is shown below.
Output:
Program 2:
import java.util.ArrayList;
import java.util.stream.Stream;
public class GFG {
public static void main(String[] args)
{
ArrayList<String> list = new ArrayList<String>();
list.add( "Aman" );
list.add( "Suraj" );
list.add( "Zufaq" );
Stream<ArrayList<String> > value
= Stream.ofNullable(list);
System.out.println( "Values of Stream:" );
value.forEach(System.out::println);
}
}
|
The output printed on console is shown below.
Output:
References: https://docs.oracle.com/javase/10/docs/api/java/util/stream/Stream.html#ofNullable(T)
Last Updated :
25 Apr, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...