In the previous article, we have seen the allMatch() method. Here we are going to discuss the Java 8 Stream anyMatch() method.
anyMatch() short-circuiting terminal operation returns true if any of the elements of the Stream matches the input predicate.
Stream anyMatch() Syntax
boolean java.util.stream.Stream.anyMatch(Predicate predicate)
anyMatch method takes the lambda expression as input that returns a Predicate.
If the first element of the Stream matches the provided predicate anyMatch() skips evaluating the remaining elements. It does short circuit evaluation and is why it is called a short-circuiting terminal operation.
We take the Candidate example from the previous post for demonstrating the anyMatch method. The part of the example is modified in this article. The score input data is modified for illustration purposes.
If any of the candidate score is greater than 70 it will return true. The second record has a score greater than 70 and the rest of the elements may be skipped from the evaluation.
Stream anyMatch() Example
//input data
public List<Candidate> getJobCandidates() {
List<Candidate> list = Arrays.asList(
new Candidate("John", "Degree", "Banking", false, 50),
new Candidate("James", "Degree", "Banking", false, 75),
new Candidate("Harry", "Degree", "Banking", true, 70),
new Candidate("Justin", "Degree", "Banking", false, 55),
new Candidate("Jennifer", "Degree", "Banking", false, 47));
return list;
}
//check for anyMatch
boolean candidatesScoreMatch = m.getJobCandidates().stream()
.anyMatch(c -> c.getScore() > 70);
System.out.println("Any Candidate Pass Score greater than 70 ? "
+ candidatesScoreMatch);
Output:
Any Candidate Pass Score greater than 70 ? true
When the Stream is empty? What will be the result of anyMatch() method?
When the stream is empty the anyMatch() operation will return false and the provided input predicate won't be evaluated.
//empty list
public List<Candidate> getJobCandidates() {
List<Candidate> list = Arrays.asList();
return list;
}
boolean candidatesScoreMatch = m.getJobCandidates().stream()
.anyMatch(c -> c.getScore() > 70);
System.out.println("Any Candidate Pass Score greater than 70 ? "
+ candidatesScoreMatch);
Output:
Any Candidate Pass Score greater than 70 ? false
In anyMatch method, we are using a lambda expression to check the score. If you try to simply lambda expression here with method reference you will get the following compilation error.
The target type of this expression must be a functional interface
//don't do this because it expects lambda expression
.anyMatch(Candidate::getScore > 70);
To fix the compiling issue and If you want to use a method reference here use it like the below way,
//to use method reference define the method in pojo
.anyMatch(Candidate::getScoreGreaterThan70);
Declare the getScoreGreaterThan70 in Candidate class to use in method reference.
In the next post, we will see the noneMatch() example.