자바의 Stream API는 JAVA 8부터 추가된 기능이다
함수형 프로그래밍을 기반으로 컬렉션, 배열과 같은 데이터를 간결하게 처리할 수 있고 병렬 처리가 가능하다
처리한 데이터 요소 중 1개를 가져오는 방법은 findFist와 findAny가 있다
findFist와 findAny 둘 다 조건에 해당하는 요소 하나를 가져오는 것은 동일하다
하지만
findFirst는 Stream의 순서에서 가장 먼저 나오는 요소를 가져오고,
findAny는 병렬로 처리할 경우 멀티 스레드에서 가장 먼저 찾은 요소를 가져온다
즉, 실행시마다 결과가 달라질 수 있다
예제
1. Bird record 생성
JAVA 14에 추가된 record 타입 클래스를 생성한다
public record Bird(String name, int age) {
}
2.
List를 생성하고 5개의 요소를 넣어준다
나이가 1인 새 중 가장 먼저 찾은 요소를 반환하는 Stream을 생성해 출력한다
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
// Bird 객체를 담는 ArrayList 생성
ArrayList<Bird> birds = new ArrayList<>();
birds.add(new Bird("참새", 1));
birds.add(new Bird("비둘기", 2));
birds.add(new Bird("갈매기", 1));
birds.add(new Bird("매", 2));
birds.add(new Bird("독수리", 1));
// findFirst()를 사용하여 첫 번째로 찾은 Bird 객체 출력
System.out.print("findFirst : ");
Bird bird = birds.stream()
.filter(b -> b.age() == 1)
.findFirst().get();
System.out.println(bird.name());
// findAny()를 사용하여 임의의 Bird 객체 출력
System.out.print("findAny : ");
Bird bird2 = birds.stream()
.filter(b -> b.age() == 1)
.findAny().get();
System.out.println(bird2.name());
// parallel()을 사용하여 병렬 스트림으로 처리한 후 findAny()를 사용하여 임의의 Bird 객체 출력
System.out.print("findAny + parallel : ");
Bird bird3 = birds.stream().parallel()
.filter(b -> b.age() == 1)
.findAny().get();
System.out.println(bird3.name());
}
}
각 Stream은 아래와 같다
Stream1 = findFirst + 직렬
Stream2 = findAny + 직렬
Stream3 = findAny + 병렬
3. 결과
병렬로 처리한 세 번째 Stream find + parallel은 첫 요소 "참새"가 아닌 "갈매기"를 가져왔다
findAny는 여러 스레드를 돌려 가장 먼저 찾은 값을 반환하기 때문에 실행할 때마다 조건에 만족하는 다른 값을 가져온다