findFirst()와 findAny()는 java.util.stream 패키지 안에 존재한다.
해당 패키지는 Java8 버전에서 새롭게 추가가 된 패키지이다.
(https://www.oracle.com/java/technologies/javase/8-whats-new.html 에서 확인가능하다)
findFirst()
첫번째 요소, 혹은 비어있는 Optional를 반환한다.
List<String> list = Arrays.asList("doyaji", "pengsoo", "hello", "doramda", "java");
Optional<String> result = list.parallelStream()
.filter(str -> str.startsWith("d"))
.findFirst();
// 반환값이 null이 아니면
if(result.isPresent()) System.out.println(result.get());
else System.out.println("null value");
// 반환값이 null이면
if(result.isEmpty()) System.out.println("null value");
else System.out.println(result.get());
findAny()
일부요소, 혹은 비어있는 Optional를 반환한다. 동작은 비결정론적 알고리즘(결정론적 알고리즘과는 달리, 동일한 입력이 주어지더라도 매번 다른 과정을 거쳐 다른 결과를 도출하는 알고리즘)을 사용한다. 안정적인 결과를 원하면 findFirst()를 사용하는게 좋다.
List<String> list = Arrays.asList("doyaji", "pengsoo", "hello", "doramda", "java");
Optional<String> result = list.parallelStream()
.filter(str -> str.startsWith("d"))
.findAny();
// 반환값이 null이 아니면
if(result.isPresent()) System.out.println(result.get());
else System.out.println("null value");
// 반환값이 null이면
if(result.isEmpty()) System.out.println("null value");
else System.out.println(result.get());