Java/스트림(Stream)

[Java]Stream 특정 조건을 만족하는지 확인하는 방법 - noneMatch 메서드

DevStory 2022. 8. 25.

noneMatch 메서드

Stream 클래스에서 제공하는 noneMatch() 메서드는 조건식에 따라 Boolean 타입의 값을 반환합니다.

boolean noneMatch(Predicate<? super T> predicate);

noneMatch 메서드 특징

  • 단락 종료 오퍼레이션(short-circulting terminal operation)입니다.
  • 매개변수는 함수형 인터페이스인 Predicate 타입입니다. Predicate 인터페이스는 한 개의 매개변수를 가지며, Boolean 타입의 값을 반환하는 작업을 수행하기 위해 사용됩니다.
  • noneMatch() 메서드의 매개변수로 전달된 Predicate 타입의 객체 또는 람다 표현식이 true를 반환하는 경우 더 이상 noneMatch() 메서드를 호출하지 않습니다.
  • 매개변수로 전달된 Predicate 객체 또는 람다 표현식이 반환하는 값의 부정을 반환합니다.
  • 스트림이 비어 있는 경우 true를 반환합니다.

예제 1. Integer 타입의 List

다음 예제는 Integer 타입의 List에서 음수인 값이 있는지 Stream 클래스의 noneMatch() 메서드로 확인합니다.

public static void main(String args[]) {
  List<Integer> intList = new ArrayList<>(Arrays.asList(0, 10, 20));

  Boolean isNoneMatchReturn =
          intList.stream().noneMatch(num -> num < 0);

  System.out.println("intList의 모든 요소는 양수인가?: " + isNoneMatchReturn);
}

[실행 결과]

intList의 모든 요소는 양수인가?: true

예제 2. noneMatch 메서드 동작 확인

다음 예제는 첫 번째 예제와 동일하지만, noneMatch() 메서드의 동작 과정을 확인하기 위해 List에 음수인 -10이 추가되었으며, 람다 표현식에 스트림 요소의 값을 출력하는 소스 코드를 추가합니다.

public static void main(String args[]) {
  List<Integer> intList = new ArrayList<>(Arrays.asList(0, 10, -10, 20));
        
  Boolean isNoneMatchReturn = intList.stream().noneMatch(num -> {
    System.out.println("현재 요소는? " + num);
    return num < 0;
  });
  
  System.out.println("intList의 모든 요소는 양수인가?: " + isNoneMatchReturn);
}

[실행 결과]

현재 요소는? 0
현재 요소는? 10
현재 요소는? -10
intList의 모든 요소는 양수인가?: false

-10 다음에 20이 존재하지만, 20은 콘솔에 출력되지 않았습니다. noneMatch() 메서드는 매개변수로 전달된 람다 표현식에서 true를 반환하는 경우 true의 부정인 false를 반환하고 더 이상 noneMatch() 메서드를 호출하지 않습니다.


예제 3. 스트림이 비어 있는 경우

noneMatch() 메서드는 anyMatch() 메서드의 반환 결과를 부정합니다.

 

따라서, 스트림이 비어 있는 경우 anyMatch() 메서드는 false를 반환하고 noneMatch() 메서드는 true를 반환합니다.

public static void main(String args[]) {
  List<Integer> intList = new ArrayList<>();
        
  Boolean isAnyMatchReturn = intList.stream().anyMatch(num -> num < 0);
  Boolean isNoneMatchReturn =intList.stream().noneMatch(num -> num < 0);

  System.out.println("스트림이 비어 있는 경우 anyMatch()의 반환 결과: " + isAnyMatchReturn);
  System.out.println("스트림이 비어 있는 경우 noneMatch()의 반환 결과: " + isNoneMatchReturn);
}

[실행 결과]

스트림이 비어 있는 경우 anyMatch()의 반환 결과: false
스트림이 비어 있는 경우 noneMatch()의 반환 결과: true
반응형

댓글