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.
false
if the stream is empty.Predicate
, then the anyMatch
method will return true
, without applying the Predicate
function on the remaining elements on the stream.boolean anyMatch(Predicate<? super T> predicate)
anyMatch
takes a Predicate
function as an argument.
true
: If at least one element in the stream matches the provided Predicate
.
false
: If all elements don’t match the provided Predicate
.
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);}}
In the code above, we:
ArrayList
with the elements:1,2,3
From the ArrayList
, we get the stream of the ArrayList
through the stream()
function.
Called the anyMatch
method with a Predicate
function. In the Predicate
function, we checked if the value is > 100
. The anyMatch
method will loop through all the elements of the stream and test each element against the passed Predicate
function. In our case, no element matches the Predicate
function because all the elements in the list are < 100
. So, false
is returned.
Added a 101
value to the ArrayList
, and called the anyMatch
method on the ArrayList
. Now the list contains one element (101
) which matches the Predicate
function.
In this case, the anyMatch
method will return true
.