ofNullable() 方法是 Stream 类的静态方法,如果非空,则返回包含单个元素的顺序 Stream,否则返回空。 Java 9 引入此方法是为了避免 NullPointerExceptions 并避免流的空检查。使用 ofNullable() 方法的主要目标是在值为 null 时返回空选项。
static <T> Stream<T> ofNullable(T t)
import java.util.stream.Stream; public class OfNullableMethodTest1 { public static void main(String args[]) { System.out.println("TutorialsPoint"); int count = (int) Stream.ofNullable(5000).count(); System.out.println(count); System.out.println("Tutorix"); count = (int) Stream.ofNullable(null).count(); System.out.println(count); } }
TutorialsPoint 1 Tutorix 0
import java.util.stream.Stream; public class OfNullableMethodTest2 { public static void main(String args[]) { String str = null; Stream.ofNullable(str).forEach(System.out::println); // prints nothing in the console str = "TutorialsPoint"; Stream.ofNullable(str).forEach(System.out::println); // prints TutorialsPoint } }
TutorialsPoint