[BE/JAVA] Stream.anyMatch().allMatch()

2023. 4. 23. 01:22
728x90
반응형

Stream

1) Iterator와 같은 외부반복자를 사용하지 않아도 데이터에 접근할 수 있음 (내부반복자 사용)

2) 한번 사용하면 close되어 다시 사용할 수 없음 (1회용)

3) parallelStream() 메소드를 사용하여 손쉽게 병렬처리가 가능

4) 람다식으로 표현하기 때문에 가독성이 좋음

출처: Baeldung

 

 

anyMatch

1) Predicate 인터페이스를 매개변수로 받아 이를 만족하는 요소가 있는 경우 true를 리턴

2) 최소 한개 이상이 조건에 만족한다면 true를 리턴

 

샘플코드

import java.util.Arrays;
import java.util.List;

public class AnyMatchExample {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

        boolean anyMatch = numbers.stream()
                                  .anyMatch(num -> num > 3);

        if (anyMatch) {
            System.out.println("최소한 하나 이상의 요소가 3보다 큽니다.");
        } else {
            System.out.println("모든 요소가 3보다 작거나 같습니다.");
        }
    }
}

 

 

allMatch

1) Predicate 인터페이스를 매개변수로 받아 이를 만족하는 모든 요소가 있는 경우 true를 리턴

2) 파라미터가 모두 조건을 만족한다면 true를 리턴

 

샘플코드

import java.util.Arrays;
import java.util.List;

public class AllMatchExample {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

        boolean allMatch = numbers.stream()
                                  .allMatch(num -> num > 0);

        if (allMatch) {
            System.out.println("모든 요소가 0보다 큽니다.");
        } else {
            System.out.println("최소한 하나의 요소가 0보다 작거나 같습니다.");
        }
    }
}
728x90
반응형

BELATED ARTICLES

more