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();
'개발&프로그래밍' 카테고리의 다른 글
[SpringSecurity] SpringSecurity에서 user detail 정보를 획득하기 (0) | 2022.03.17 |
---|---|
[JUnit] JUnit5 기본 설정 및 어노테이션 (0) | 2022.03.16 |
[Kotlin] 코틀린 클래스와 프로퍼티 (0) | 2022.03.15 |
[Spring] @SpringBootApplication 어노테이션 (0) | 2022.03.15 |
[Spring] 스프링 웹 어노테이션 (Spring Web Annotation) (0) | 2022.03.15 |
댓글