In the last post, we have discussed the Java 8 Stream allMatch() and anyMatch() methods. This post explains about the
usage of noneMatch() method.
Stream noneMatch() Syntax
boolean java.util.stream.Stream.noneMatch(Predicate predicate)
noneMatch evaluates the given input predicate and returns true or false.
Stream noneMatch() works exactly opposite to anyMatch() method. If no elements of the Stream match the given predicate it will return true otherwise it returns false. In simple terms, none of the elements of the Stream match the provided predicate noneMatch() returns true.
If the Stream is empty also it will return true. For an empty Stream, it won't evaluate the input predicate.
Stream noneMatch() method is a short-circuiting terminal operation.
Stream noneMatch() Example
For complete code look at the allMatch() method article.
public List<Candidate> getJobCandidates() {
List<Candidate> list = Arrays.asList(
new Candidate("John", "Degree", "Banking", false, 70),
new Candidate("James", "Degree", "Banking", false, 75),
new Candidate("Harry", "Degree", "Banking", true, 79),
new Candidate("Justin", "Degree", "Banking", false, 95),
new Candidate("Jennifer", "Degree", "Banking", false, 87));
return list;
}
boolean candidatesScoreMatch = m.getJobCandidates().stream()
.noneMatch(c -> c.getScore() < 70);
Output:
None of the Candidate Score less than 70 ? true
Say the passing score of the candidate is 70. We need to check all candidates were passed the exam. As we are using noneMatch we have to use the lesser than symbol to check the score. If you are using anyMatch change it to greater than symbol to check all candidates cleared the Banking test.
If none of the Candidate is scored less than pass score seventy it will return true.
Let's see a noneMatch() example with an empty list,
public List<Candidate> getJobCandidates() {
List<Candidate> list = Arrays.asList();
return list;
}
//noneMatch code goes here
Output:
None of the Candidate Score less than 70 ? true
Hope you got a clear idea about noneMatch() method. In the later posts, we will deep dive into it by comparing it with other operations.