the anyMatch()
, allMatch()
, and noneMatch()
methods are used to check if any, all, or none of the elements in a stream match a certain condition.
AnyMatch Example Code
anyMatch(Predicate<T> predicate)
returns true
if any element in the stream matches the given predicate.
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
boolean evenNumber= numbers.stream().anyMatch(n -> n % 2 == 0);
AllMatch Example Code
allMatch(Predicate<T> predicate)
returns true
if all elements in the stream match the given predicate.
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
boolean allEven = numbers.stream().allMatch(n -> n % 2 == 0);
noneMatch Example Code
noneMatch(Predicate<T> predicate)
returns true
if no element in the stream matches the given predicate.
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
boolean noEven = numbers.stream().noneMatch(n -> n % 2 == 0);
It’s important to note that these methods are short-circuiting, meaning that as soon as a match is found (or not found, in the case of noneMatch()
), the stream processing is stopped and the result is returned.
Java Code
public class AllMatch {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
boolean evenNumber= numbers.stream().anyMatch(n -> n % 2 == 0);
boolean allEven = numbers.stream().allMatch(n -> n % 2 == 0);
boolean noEven = numbers.stream().noneMatch(n -> n % 2 == 0);
System.out.println("evenNumber:"+evenNumber);
System.out.println("allEven:"+allEven);
System.out.println("noEven:"+noEven);
}
}
Output:
evenNumber:true
allEven:false
noEven:false
Thanks for Reading…