[Java] Stream API의 anyMatch(), allMatch(), noneMatch()
※ 일본의 한 블로그 글을 번역한 포스트입니다. 오역 및 의역, 직역이 있을 수 있으며 틀린 내용은 지적해주시면 감사하겠습니다.
anyMatch: 판정 (일부 일치)
anyMatch 메소드는 filter 메소드에도 사용할 수 있으며, 판정하기 위해 함수형 인터페이스인 Predicate<T>를 인수로 받아, boolean(1개라도 조건에 일치하는 값이 있다면 true)를 반환한다.
조건에 일치하는 값이 발견됐을 시점에 처리를 종료하므로 ||와 동일하다.
anyMatch의 사용법
String의 Collection에서 문자열을 검색하는 샘플 코드를 살펴보자.
List<String> strs = Arrays.asList("hoge", "fuga", "bars");
// 람다식
boolean b = strs.stream().anyMatch(s -> s.equals("fuga"));
System.out.println(b);
// 익명클래스
boolean b = strs.stream().anyMatch(new Predicate<String>() {
@Override
public boolean test(String t) {
return t.equals("fuga");
}
});
// 실행결과
true
빈 Stream의 경우는 false를 반환하므로, 특별한 문제는 없다.
boolean c = Stream.empty().anyMatch(s -> s.equals("fuga"));
System.out.println(c);
// 실행결과
false
allMatch : 판정(모두 일치)
allMatch 메소드는 함수현 인터페이스인 Predicate<T>를 받아, boolean(모든 조건에 일치하는 값이어야 true)를 반환한다. 조건에 일치하지 않은 값이 발견된 시점에 처리가 종료되므로 &&와 동일하다.
allMatch의 사용법
String의 Collection에서 문자수를 판정하는 샘플코드이다.
private static boolean isCheckLength(Stream<String> s) {
return s.allMatch(str -> str.length() == 4);
}
...
List<String> strs = Arrays.asList("hoge", "fuga", "bars");
System.out.println(isCheckLength(strs.stream()));
// 실행결과
true
빈 Stream의 경우는 true를 반환한다.
private static boolean isCheckLength(Stream<String> s) {
return s.allMatch(str -> str.length() == 4);
}
...
System.out.println(isCheckLength(Stream.empty()));
// 실행결과
true
noneMatch : 판정(모두 비일치)
noneMatch 메소드는 함수형 인터페이스인 Predicate<T>를 인수로 받아, boolean(조건에 일치하는 값이 하나도 없다면 true)를 반환한다. 조건에 일치하는 값이 발견된 시점에서 종료된다.
noneMatch의 사용법
String의 Collection에서 문자수를 판정하는 샘플코드이다.
List<String> strs = Arrays.asList("hoge", "fuga", "bars");
boolean d = strs.stream().noneMatch(s -> s.equals("foo"));
System.out.println(d);
// 실행결과
true
빈 Stream의 경우는 true를 반환한다.
boolean d = Stream.empty().noneMatch(s -> s.equals("foo"));
System.out.println(d);
// 실행결과
true
참고자료
https://www.task-notes.com/entry/20150521/1432177200
https://java-beginner.com/stream-api-allmatch-anymatch-nonematch/