ofNullable() 方法是 Stream 类的静态方法,如果非空,则返回包含单个元素的顺序 Stream,否则返回空。 Java 9 引入此方法是为了避免 NullPointerExceptions 并避免流的空检查。使用 ofNullable() 方法的主要目标是在值为 null 时返回空选项。
<strong>static <T> Stream<T> ofNullable(T t)</strong>
import java.util.stream.Stream; public class OfNullableMethodTest1 { public static void main(String args[]) { System.out.println("TutorialsPoint"); int count = (int) Stream.<strong>ofNullable</strong>(5000).count(); System.out.println(count); System.out.println("Tutorix"); count = (int) Stream.<strong>ofNullable</strong>(null).count(); System.out.println(count); } }
<strong>TutorialsPoint 1 Tutorix 0</strong>
import java.util.stream.Stream; public class OfNullableMethodTest2 { public static void main(String args[]) { String str = null; Stream.<strong>ofNullable</strong>(str).forEach(System.out::println); <strong>// prints nothing in the console</strong> str = "TutorialsPoint"; Stream.<strong>ofNullable</strong>(str).forEach(System.out::println); <strong>// prints TutorialsPoint</strong> } }
<strong>TutorialsPoint</strong>
以上就是在Java 9中什么时候使用Stream的ofNullable()方法?的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号