何时在 Java 9 中使用 Stream 的 ofNullable() 方法?\
javaobject oriented programmingprogramming更新于 2025/7/13 5:32:17
ofNullable() 方法是 Stream 类的静态方法,如果非空,则返回包含单个元素的顺序 Stream,否则返回空。Java 9 引入了此方法,以避免 NullPointerExceptions 并避免对流进行 null 检查。使用 ofNullable() 方法的主要目的是,如果值为空,则返回 empty 选项。
语法
static <T> Stream<T> ofNullable(T t)
Example-1
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
示例 2
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
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

