JB Header
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 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)
Where,
     - input is 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.
Java 8 code showing Stream.allMatch() method usage
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);
  }
}
 OUTPUT of the above code
All employees are above 21:true
Explanation of the code
  • Employee is the class of which we will be creating a Stream. It has two main attributes - name and age.
  • employeeList is a static list of 5 Employees.
  • In the main() method we create a Stream of Employees using the stream() method of List interface.
  • On the stream of Employees we call the allMatch() method with the Predicate 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 the Employees, and the allMatch() method returns true.
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)
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.

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.)
Java 8 code showing Stream.anyMatch() method usage
public static void main(String[] args) {
  boolean empAbove40 = employeeList.stream()
                      .anyMatch(emp -> emp.getAge() > 40);
  System.out.println("Any employee is above 40:" + empAbove40);
}
 OUTPUT of the above code
Any employee is above 40:true
Explanation of the code
  • In the main() method we create a Stream of Employees using the stream() method of List interface.
  • On the stream of Employees we call the anyMatch() method with the Predicate 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 returns true.
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)
Where,
     - input is 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.)
Java 8 code showing Stream.noneMatch() method usage
public static void main(String[] args) {
  boolean noEmpBelow30 = employeeList.stream()
                        .noneMatch(emp -> emp.getAge() < 30);
    System.out.println("No employee is below 30:" + noEmpBelow30);
}
 OUTPUT of the above code
No employee is below 30:false
Explanation of the code
  • In the main() method we create a Stream of Employees using the stream() method of List interface.
  • On the stream of Employees we call the noneMatch() method with the Predicate 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 returns false. For the method to return true - none of the employees in the employeeList should have age less than 30 years.
Conclusion In this tutorial we learnt what is meant by matching in the context of Java 8 Streams. Next we looked at the definition and code usage of three methods provided by Streams API for the purpose of matching - allMatch(), anyMatch() and noneMatch().