什么时候在 Java 9 中使用 Stream 的 ofNullable() 方法?
ofNullable() 方法是 Stream 类的静态方法,如果非空则返回含有一个元素的顺序 Stream,否则返回一个空 Stream。Java 9 中引入了这种方法来避免 NullPointerExceptions 和避免 Stream 的空值检查。使用 ofNullable() 方法的主要目的是,如果值为 null,则返回空的 Optional。
语法
static <T> Stream<T> ofNullable(T t)
示例 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP