프로그래밍 노트/JAVA

[JAVA] Stream 매칭(allMatch(), anyMatch(), noneMatch())

깡냉쓰 2020. 1. 7. 21:30
728x90
반응형

Stream API는 최종 처리 단계 에서 요소들이 특정 조건에 만족하는지 조사할 수 있도록 세가지 매칭 메소드를 제공한다.
allMatch() 모든 요소들이 매개값으로 주어진 Predicate의 조건을 만족하는지 조사
anyMatch() 최소한 한 개의 요소가 매개값으로 주어진 조건을 만족하는지 조사
noneMatch() 모든 요소들이 매개값으로 주어진 조건을 만족하지 않는지 조사

public static void main(String[] args){
        int[] intArr = {2, 4, 6};

        boolean result = Arrays.stream(intArr)
                .allMatch(a -> a%2 == 0);
        System.out.println("2의 배수? " + result);

        result = Arrays.stream(intArr)
                .anyMatch(a -> a%3 == 0);
        System.out.println("3의 배수가 하나라도 있나? " + result);

        result = Arrays.stream(intArr)
                .noneMatch(a -> a%3 == 0);
        System.out.println("3의 배수가 없나? " + result);
}

2의 배수? true
3의 배수가 하나라도 있나? true
3의 배수가 없나? false

출처 : 이것이 자바다.

728x90
반응형