본문 바로가기
개발&프로그래밍

[JAVA] Java8 Stream API - findFirst() 와 findAny()

by 재아군 2022. 3. 15.

Java8 Stream API - findFirst() 와 findAny()에 대해 알아봅니다.

 

Stream.findAny()

Stream 에서 모든 요소를 ​​찾을 수 있습니다. 
이 메서드는 Stream 이 비어 있는 경우 비어 있는 Optional 인스턴스를 반환합니다.

@Test
public void testFindAny() {
    List<String> list = Arrays.asList("1","2","3");
    Optional<String> result = list.stream().findAny();

    assertTrue(result.isPresent());
    assertThat(result.get(), anyOf(is("1"), is("2"), is("3")));
}

병렬이 아닌 작업에서는 Stream 의 첫 번째 요소를 반환할 가능성이 높지만 이에 대한 보장은 없습니다.

 

 

 

Stream의 findAny 메소드 살펴보기

    /**
     * Returns an {@link Optional} describing some element of the stream, or an
     * empty {@code Optional} if the stream is empty.
     *
     * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
     * terminal operation</a>.
     *
     * <p>The behavior of this operation is explicitly nondeterministic; it is
     * free to select any element in the stream.  This is to allow for maximal
     * performance in parallel operations; the cost is that multiple invocations
     * on the same source may not return the same result.  (If a stable result
     * is desired, use {@link #findFirst()} instead.)
     *
     * @return an {@code Optional} describing some element of this stream, or an
     * empty {@code Optional} if the stream is empty
     * @throws NullPointerException if the element selected is null
     * @see #findFirst()
     */
    Optional<T> findAny();

 

Stream.findFirst()


findFirst() 메서드는 Stream 에서 첫 번째 요소를 찾습니다. 시퀀스의 첫 번째 요소를 구체적으로 원할 때 이 방법을 사용합니다.

return type은 Stream 도 비어 있는 경우에는 비어 있는 Optional 인스턴스이기도 합니다 .



@Test
public void testFindFirst() {
    List<String> list = Arrays.asList("1", "2", "3");

    Optional<String> result = list.stream().findFirst();

    assertTrue(result.isPresent());
    assertThat(result.get(), is("1"));
}

 

 

 

Stream의 findFirst 메소드 살펴보기

    /**
     * Returns an {@link Optional} describing the first element of this stream,
     * or an empty {@code Optional} if the stream is empty.  If the stream has
     * no encounter order, then any element may be returned.
     *
     * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
     * terminal operation</a>.
     *
     * @return an {@code Optional} describing the first element of this stream,
     * or an empty {@code Optional} if the stream is empty
     * @throws NullPointerException if the element selected is null
     */
    Optional<T> findFirst();

 

댓글