What is the anyMatch() method of the Stream Interface?
The anyMatch method of the Stream Interface can be used to check if at least one element of the stream matches or satisfies the provided
The anyMatch method is a short-circuiting terminal operation.
- It will return
falseif the stream is empty. - If any element matches the
Predicate, then theanyMatchmethod will returntrue, without applying thePredicatefunction on the remaining elements on the stream.
Syntax
boolean anyMatch(Predicate<? super T> predicate)
Parameter
anyMatch takes a Predicate function as an argument.
Return value
-
true: If at least one element in the stream matches the providedPredicate. -
false: If all elements don’t match the providedPredicate.
Code
import java.util.ArrayList;class AnyMatchTest {public static void main( String args[] ) {ArrayList<Integer> numbers = new ArrayList<>();numbers.add(1);numbers.add(2);numbers.add(3);System.out.println("The numbers list is " + numbers);boolean hasNumber;hasNumber = numbers.stream().anyMatch((number) -> number > 100 );System.out.println("Cheking if a number > 100 is present in list - " + hasNumber);numbers.add(101);System.out.println("\nAdded 101 to the numbers list now the list is - " + numbers);hasNumber = numbers.stream().anyMatch((number) -> number > 100 );System.out.println("Cheking if a number > 100 is present in list - " + hasNumber);}}
Explanation
In the code above, we:
- Created an
ArrayListwith the elements:
1,2,3
-
From the
ArrayList, we get the stream of theArrayListthrough thestream()function. -
Called the
anyMatchmethod with aPredicatefunction. In thePredicatefunction, we checked if the value is> 100. TheanyMatchmethod will loop through all the elements of the stream and test each element against the passedPredicatefunction. In our case, no element matches thePredicatefunction because all the elements in the list are< 100. So,falseis returned. -
Added a
101value to theArrayList, and called theanyMatchmethod on theArrayList. Now the list contains one element (101) which matches thePredicatefunction. In this case, theanyMatchmethod will returntrue.