Java 8 Matching with Streams | allMatch, anyMatch, noneMatch methods tutorial with examples
Introduction - Java 8 Matching with Streams tutorial explains how to match elements in a stream using the
Where,
- input is
Where,
- input is
Where,
- input is
allMatch()
, anyMatch()
and noneMatch()
methods provided by the Streams API with examples to show their usage. This tutorial assumes that you are familiar with basics of Java 8 Streams APIRead Basics of Java 8 Streams API.
What is 'matching' in the context of Streams
Given a stream of objects, many-a-times we need to check whether object(s) in the given stream match a specific criteria. Instead of writing logic for iterating over the stream elements and checking each object whether it matches the criteria (which is more of an imperative rather than functionalClick to understand the difference between the two programming styles style of programming), Java 8 Streams allow declarative matching of objects in the stream.
I.e. once you define the condition using a Predicate instance, and provide this Predicate as an input to the matching methods, then Java 8 processes the matching function internally and provides you with the result whether a match for the condition was found or not.
Java 8 provides such declarative matching with predicate conditions using three methods defined on the Streams API which are - allMatch()
, anyMatch()
and noneMatch()
.
Stream.allMatch()
method
Stream.allMatch()
method returns true
if all the elements of the stream match the provided predicate condition. If even one of the elements does not match the predicate condition then the method skips the testing of the remaining elements using the concept of short-circuit evaluationClick to read in-depth article on Short-Circuits in Programming and returns false
as the result. This is a terminalClick to Read Tutorial explaining intermediate & terminal Stream operations stream operation.
Definition of allMatch()
Method - The Stream.allMatch()
method has the following signature -
boolean allMatch(Predicate<? super T> predicate)
predicate
which is an instance of a Predicate Functional InterfaceClick to read detailed tutorial on Predicate Functional Interfaces
- boolean
value is returned indicating whether all elements of the stream match the predicate
or not.
The below code shows how to use the allMatch()
method in your code.
[su_box title="Java 8 code showing Stream.allMatch() method usage" style="soft" box_color="#fcba43" title_color="#00000" radius="4" Class="for-shortcodebox"][java]package com.javabrahman.java8;
public class Employee{
private String name;
private Integer age;
public Employee(String name, Integer age){
this.name=name;
this.age=age;
}
//getters and setters for name and age attributes go here
//overridden equals() and hashcode() go here
public String toString(){
return "Employee Name:"+this.name
+" Age:"+this.age;
}
}
//MatchingWithStreams.java
public class MatchingWithStreams {
static List<Employee> employeeList = Arrays.asList(new Employee("Tom Jones", 45),
new Employee("Harry Major", 25),
new Employee("Ethan Hardy", 65),
new Employee("Nancy Smith", 22),
new Employee("Deborah Sprightly", 29));
public static void main(String[] args) {
boolean allEmpAbove21 = employeeList.stream()
.allMatch(emp -> emp.getAge() > 21);
System.out.println("All employees are above 21:" + allEmpAbove21);
}
}[/java][/su_box]
OUTPUT of the above code[su_note note_color="#1a1a1a" text_color="#DAD9D7"]All employees are above 21:true[/su_note]
Explanation of the code
Employee
is the class of which we will be creating aStream
. It has two main attributes -name
andage
.employeeList
is a static list of 5Employee
s.- In the
main()
method we create aStream
ofEmployee
s using thestream()
method ofList
interface. - On the stream of Employees we call the
allMatch()
method with thePredicate
instance being specified as its equivalent lambda expressionClick to read tutorial on Java 8 Lambda Expressions -emp -> emp.getAge() > 21
. This predicate condition states that the Employee's age should be greater than 21 years. - Since, all the employees are of age greater than 21 years, so the
Predicate
is satisfied for all theEmployee
s, and theallMatch()
method returnstrue
.
Stream.anyMatch()
method
Stream.anyMatch()
method returns true
if at least 1 of the elements of the stream match the provided predicate condition. If none of the elements match the predicate condition then the method returns false
. The moment this method finds the first element satisfying the predicate, it skips the testing of the remaining elements using the concept of short-circuit evaluation and returns true
as the result. This is a terminal stream operation.
Definition of anyMatch()
Method - The Stream.anyMatch()
method has the following signature -
boolean anyMatch(Predicate<? super T> predicate)
predicate
which is an instance of a Predicate Functional Interface
- boolean
value is returned indicating whether any of the elements of the stream match the predicate
or not.
The below code shows how to use the anyMatch()
method in your code.
(Note - The Employee
class and employeeList
objects with their values remain the same as the previous code usage example and hence are not shown below for brevity.)
[su_box title="Java 8 code showing Stream.anyMatch() method usage" style="soft" box_color="#fcba43" title_color="#00000" radius="4" Class="for-shortcodebox"][java]public static void main(String[] args) {
boolean empAbove40 = employeeList.stream()
.anyMatch(emp -> emp.getAge() > 40);
System.out.println("Any employee is above 40:" + empAbove40);
}[/java][/su_box]
OUTPUT of the above code[su_note note_color="#1a1a1a" text_color="#DAD9D7"]Any employee is above 40:true[/su_note]
Explanation of the code
- In the
main()
method we create aStream
ofEmployee
s using thestream()
method ofList
interface. - On the stream of Employees we call the
anyMatch()
method with thePredicate
instance being specified as its equivalent lambda expression -emp -> emp.getAge() > 40
. This predicate condition states that the Employee's age should be greater than 40 years. - Since, there are 2 employees of age greater than 40 years, the predicate is satisfied and the
anyMatch()
method returnstrue
.
Stream.noneMatch()
method
Stream.noneMatch()
method returns true
if none of the elements of the stream match the provided predicate condition. If one (or more) of the elements match the predicate condition then the method returns false
. The moment this method finds the first element satisfying the predicate, it skips the testing of the remaining elements using the concept of short-circuit evaluation and returns false
as the result. This is a terminal stream operation.
Definition of noneMatch()
Method - The Stream.noneMatch()
method has the following signature -
boolean noneMatch(Predicate<? super T> predicate)
predicate
which is an instance of a Predicate Functional Interface
- boolean
value is returned indicating whether none of the elements of the stream match the predicate
.
The below code shows how to use the noneMatch()
method in your code.
(Note - The Employee
class and employeeList
objects with their values remain the same as the previous code usage example and hence are not shown below for brevity.)
[su_box title="Java 8 code showing Stream.noneMatch() method usage" style="soft" box_color="#fcba43" title_color="#00000" radius="4" Class="for-shortcodebox"][java]public static void main(String[] args) {
boolean noEmpBelow30 = employeeList.stream()
.noneMatch(emp -> emp.getAge() < 30);
System.out.println("No employee is below 30:" + noEmpBelow30);
}[/java][/su_box]
OUTPUT of the above code[su_note note_color="#1a1a1a" text_color="#DAD9D7"]No employee is below 30:false[/su_note]
Explanation of the code
- In the
main()
method we create aStream
ofEmployee
s using thestream()
method ofList
interface. - On the stream of Employees we call the
noneMatch()
method with thePredicate
instance being specified as its equivalent lambda expression -emp -> emp.getAge() < 30
. This predicate condition states that the Employee's age should be less than 30 years. - Since, there are 3 employees of age less than 30 years, the
noneMatch()
method returnsfalse
. For the method to returntrue
- none of the employees in theemployeeList
should have age less than 30 years.
allMatch()
, anyMatch()
and noneMatch()
.
[su_note note_color="#fbfbc4" text_color="#000000" radius="4"]Java 8 Streams API tutorials on JavaBrahman
Streams API - Introduction & BasicsClick to Read tutorial on Streams API Basics Understanding Stream Operations | Intermediate and Terminal OperationsClick to Read Tutorial on Stream Operations Overview Mapping with Streams using map and flatMap methodsClick to Read how Mapping with Java8 Streams works Filtering and Slicing with Streams using filter,distinct,limit,skip methodsClick to Read how Filtering and Slicing with Java8 Streams works Matching with Streams using allMatch,anyMatch,noneMatch methodsClick to Read tutorial on matching with Streams API Stream API's findFirst,findAny methods' tutorialClick to Read tutorial on findFirst() and findAny() methods of Streams API 'Peeking' into a running Stream with Stream.peek() methodClick to Read tutorial on Stream.peek() method Creating Infinite Streams with iterate\generate methodsClick to Read tutorial on Creating Infinite Streams Reducing Streams using Streams.reduce methodClick to Read tutorial on Reducing Streams
[/su_note]