Java 8 Streams: allMatch(), anyMatch(), noneMatch() Example
Hello readers, Java 8 Matching with Streams tutorial explains how to match the elements in a stream using the allMatch()
, anyMatch()
and noneMatch()
methods provided by the Streams API.
Table Of Contents
1. Introduction
Given a stream of objects, many-a-times developers need to check whether the object(s) in the given stream match the specific criteria or not. Instead of writing the logic for iterating over the stream elements and checking each object whether it matches the criteria (which is more of an imperative rather than the functional style of programming), Java 8 Streams allow the declarative matching of objects in the stream.
Once developers define the condition using a Predicate instance and provide this Predicate as an input argument to the matching methods, Java 8 processes the matching function internally and provides developers with the result whether a match for the condition was found or not.
Java 8 provides such declarative matching with the predicate conditions using the three methods defined on the Streams API which are: allMatch()
, anyMatch()
and noneMatch()
.
1.1 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 evaluation and returns false
as the result. This is a terminal stream operation.
The Stream.allMatch()
method has the following signature:
boolean allMatch(Predicate<? super T> predicate)
Where,
- Input is predicate which is an instance of a Predicate Functional Interface
- Boolean value is returned indicating whether all elements of the stream match the predicate or not
1.2 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.
The Stream.anyMatch()
method has the following signature:
boolean anyMatch(Predicate<? super T> predicate)
Where,
- Input is 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
1.3 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.
The Stream.noneMatch()
method has the following signature:
boolean noneMatch(Predicate<? super T> predicate)
Where,
- Input is 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
Now, open up the Eclipse Ide and let’s see a few examples of Matching in Java!
2. Java 8 Streams Example
2.1 Tools Used
We are using Eclipse Kepler SR2, JDK 8 and Maven.
2.2 Project Structure
Firstly, let’s review the final project structure, in case you are confused about where you should create the corresponding files or folder later!
2.3 Project Creation
This section will demonstrate on how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project
.
In the New Maven Project window, it will ask you to select project location. By default, ‘Use default workspace location’ will be selected. Select the ‘Create a simple project (skip archetype selection)’ checkbox and just click on next button to proceed.
It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT
.
Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml
file will be created. It will have the following code:
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>JavaMatchingEx</groupId> <artifactId>JavaMatchingEx</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> </project>
Developers can start adding the dependencies that they want. Let’s start building the application!
3. Application Building
Below are the steps involved in developing this application.
3.1 Java Class Creation
Let’s create the required Java files. Right-click on the src/main/java
folder, New -> Package
.
A new pop window will open where we will enter the package name as: com.jcg.java
.
Once the package is created in the application, we will need to create the model and the implementation classes to illustrate the Java 8 Stream examples. Right-click on the newly created package: New -> Class
.
A new pop window will open and enter the file name as: Employee
. The model (i.e. POJO
) class will be created inside the package: com.jcg.java
.
Repeat the step (i.e. Fig. 7) and enter the filename as MatchDemo
. This implementation class will be created inside the package: com.jcg.java
.
3.1.1 Implementation of Model Class
To illustrate the Stream’s usage with the help of multiple examples, we will use a simple POJO
that defines a set of employee constraint’s. Let’s see the simple code snippet that follows this implementation.
Employee.java
package com.jcg.java; import java.util.ArrayList; import java.util.List; public class Employee { public int id, sal; public String name; public Employee() { } public Employee(int id, String name, int sal) { this.id = id; this.name = name; this.sal = sal; } public static List<Employee> getEmpList() { List<Employee> empList = new ArrayList<Employee>(); empList.add(new Employee(1, "A", 2000)); empList.add(new Employee(2, "B", 3000)); empList.add(new Employee(3, "C", 4000)); empList.add(new Employee(4, "D", 5000)); return empList; } }
3.1.2 Implementation of Streams Class
To illustrate the Stream’s usage with the help of multiple examples, developers will have to use ‘JDK 1.8’. Let’s see the simple code snippet that follows this implementation.
MatchDemo.java
package com.jcg.java; import java.util.List; import java.util.function.Predicate; public class MatchDemo { private static void matchingWithStreams() { Predicate<Employee> p1 = e -> e.id < 10 && e.name.startsWith("A"); Predicate<Employee> p2 = e -> e.sal < 10000; List<Employee> eList = Employee.getEmpList(); /***** Example #1 - Using 'allMatch' *****/ boolean b1 = eList.stream().allMatch(p1); System.out.println("All employees having 'eid<10' & 'ename.equalsIgnoreCase('A')'?= " + b1 + "\n"); boolean b2 = eList.stream().allMatch(p2); System.out.println("All employees having 'esalary<10000'?= " + b2 + "\n"); /***** Example #2 - Using 'anyMatch' *****/ boolean b3 = eList.stream().anyMatch(p1); System.out.println("Any employee having 'eid<10' & 'ename.equalsIgnoreCase('A')'?= " + b3 + "\n"); boolean b4 = eList.stream().anyMatch(p2); System.out.println("Any employee having 'esalary<10000'?= " + b4 + "\n"); /**** Example #3 - Using 'noneMatch' *****/ boolean b5 = eList.stream().noneMatch(p1); System.out.println("No employee having 'esalary<10000'?= " + b5); } public static void main(String[] args) { matchingWithStreams(); } }
Do remember, developers will have to use the ‘JDK 1.8’ dependency for implementing the Stream’s usage in their applications.
4. Run the Application
To run the application, right-click on the MatchDemo
class -> Run As -> Java Application
. Developers can debug the example and see what happens after every step!
5. Project Demo
The application shows the following logs as output for the MatchDemo.java
. This following example shows how to use the allMatch()
, anyMatch()
and noneMatch()
methods of the Stream class.
All employees having 'eid<10' & 'ename.equalsIgnoreCase('A')'?= false All employees having 'esalary<10000'?= true Any employee having 'eid<10' & 'ename.equalsIgnoreCase('A')'?= true Any employee having 'esalary<10000'?= true No employee having 'esalary<10000'?= false
That’s all for this post. Happy Learning!!
6. Conclusion
That’s all for Java 8 Stream interface and developers can use it to check whether a lambda expression condition is true or false. I hope this article served you whatever you were looking for.
7. Download the Eclipse Project
This was an example of Java Predicate for the beginners.
You can download the full source code of this example here: JavaMatchingEx