[JAVA]Stream 검색과 매칭

2022. 10. 5. 19:01 JAVA BASIC/Lambda&Stream(람다와 스트림)

1. Predicate가 적어도 한 요소와 일치하는지 확인 - anyMatch

if(menu.stream().anyMatch(Dish::isVegetarian)) {
    System.out.prinln("The menu is (somewhat) vegetarian friendly!!");
}

anyMatch는 불리언을 반환하므로 최종 연산이다.

2. Predicate가 모든 요소와 일치하는지 검사 - allMatch, noneMatch

allMatch메서드는 anyMatch와 달리 모든 요소가 Predicate와 일치하는지 검사한다.

boolean isHealthy = menu.stream().allMatch(d -> d.getCalories() < 1000);

noneMatch는 allMatch와 반대 연산을 수행한다. 즉, noneMatch는 주어진 프레디케잍와 일치하는 요소가 없는지 확인한다.

boolean isHealthy = menu.stream().noneMatch(d -> d.getCalories() >= 1000);

anyMatch, allMaych, noneMatch 는 쇼트서킷 기법 연산을 활용한다.

3. 요소 검색 - findAny

findAny 메서드는 현재 스트림에서 임의의 요소를 반환한다. findAny 메서드를 다른 스트림연산과 연결해서 사용할 수 있음

Optional<Dish> dish = 
    menu.stream().filter(Dish::isVegetarian).findAny();

4. 첫 번째 요소 찾기

리스트 또는 정렬된 연속 데이터로부터 생성된 스트림처럼 일부 스트림에서는 논리적인 아이템 순서가 정해져 있을 수 있다. 이런 스트림에서 첫 번째 요소를 찾으려면 어떻게 해야 할까?

// 숫자 리스트에서 3으로 나누어떨어지는 첫 번째 제곱값을 반환하는 코드
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
numbers.stream()
    .filter(n -> n % 3 ==0)
    .map(n -> n * n)
    .findFirst(); // 9

findFirst와 findAny는 언제 사용하나?

병렬성때문에 두 메서드가 모두 필요하다. 병렬 실행에서는 첫 번째 요소를 찾기 어렵다. 따라서 요소의 반환 순서가 상관없다면 병렬 스트림에서는 제약이 적은 findAny를 사용한다.

 

출처: https://cornswrold.tistory.com/543 [평범한개발자노트:티스토리]