This method was added from Java 9.
1 |
static<T> Stream<T> ofNullable(T t) |
This method will return the Stream object of an element in case this element is not null; if it is null, it returns an empty Stream.
Example:
1 2 3 4 5 6 7 8 9 10 11 |
package com.huongdanjava.javaexample; import java.util.stream.Stream; public class Example { public static void main(String[] args) { String s = null; Stream.ofNullable(s).forEach(System.out::println); } } |
When you run the above code, it will print nothing in the console. But if you edit the variable s, not null:
1 2 3 4 5 6 7 8 9 10 11 |
package com.huongdanjava.javaexample; import java.util.stream.Stream; public class Example { public static void main(String[] args) { String s = "Khanh"; Stream.ofNullable(s).forEach(System.out::println); } } |
then the result will be: