• 카테고리

    질문 & 답변
  • 세부 분야

    프로그래밍 언어

  • 해결 여부

    미해결

findFirst함수

22.08.19 11:04 작성 조회수 185

0

findFirst함수를 쓰면 optional로 감싸져서 나온다고 하셨는데

of로 감싸지는 건지 아니면 ofNullable로 감싸지는 건지 궁금합니다.

답변 1

답변을 작성해보세요.

1

안녕하세요.  of가 사용될겁니다. Stream 인터페이스 문서에 따르면 인자 자체가 null인 경우에는 NullPE 발생한다고 해놨으니, 구현체에서 아마도 해당 요소가 null인지 호가인해서 null이면 예외를 던지고 null아 아닌 경우에만 of로 감싸서 리턴하겠네요. 물론, 해당하는 요소를 못찾은 경우에는 Optional.empty()를 리턴할테구요.

Optional<T> findFirst()
Returns an Optional describing the first element of this stream, or an empty Optional if the stream is empty. If the stream has no encounter order, then any element may be returned.

This is a short-circuiting terminal operation.

Returns:
an Optional describing the first element of this stream, or an empty Optional if the stream is empty
Throws:
NullPointerException - if the element selected is null