>  기사  >  Java  >  Java 9에서 Stream의 ofNullable() 메소드를 언제 사용합니까?

Java 9에서 Stream의 ofNullable() 메소드를 언제 사용합니까?

WBOY
WBOY앞으로
2023-08-26 13:21:071258검색

在Java 9中什么时候使用Stream的ofNullable()方法?

ofNullable() 메서드는 Stream 클래스의 정적 메서드로, null이 아닌 경우 단일 요소가 포함된 순차 스트림을 반환하고, 그렇지 않으면 비어 있는 것을 반환합니다. Java 9 이 방법은 NullPointerExceptions을 방지하고 스트림에 대한 null 검사를 방지하기 위해 도입되었습니다. ofNullable() 메서드를 사용하는 주요 목표는 값이 null일 때 null 옵션을 반환하는 것입니다.

구문 H2>
<strong>static <T> Stream<T> ofNullable(T t)</strong>

예제 1

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);
   }
}

Output

<strong>TutorialsPoint
1
Tutorix
0</strong>

예제 2

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>
   }
}

Output

<strong>TutorialsPoint</strong>

위 내용은 Java 9에서 Stream의 ofNullable() 메소드를 언제 사용합니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 tutorialspoint.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제