Java 8 – Stream anyMatch() method with examples

In this article, we will discuss Stream’s anyMatch() method in details with examples

Read below methods which are similar to anyMatch() method

1. Stream anyMatch() method :

  • This Stream method is a terminal operation which returns true for the provided Predicate, otherwise returns false
  • In other words, anyMatch() method returns true if at least any one of the element of the original Stream satisfies the provided Predicate condition, else false
  • Stream’s anyMatch() method is stateless which means it is non-interfering with other elements in the stream
  • May not evaluate the predicate on all elements if not necessary for determining the result
  • It is a short-circuiting terminal operation, as Stream pipeline ends on the first match of the provided Predicate
  • If the stream is empty then false is returned and the predicate is not evaluated
  • Method signature :- boolean anyMatch(Predicate<? super T> predicate)



2. Stream anyMatch() method examples :

2.1 To find specific element present or not

  • First list contains integers numbers
  • For integer list, we are applying Predicate condition to find if there is any number greater than 9 and 10 and it returns true for 1st condition and false for second condition
  • Second list contains String elements and we are trying to find specific element by providing Predicate condition
  • anyMatch() returns true for the satisfied condition if at least one element is present in the given Stream
package net.bench.resources.stream.anymatch.example;

import java.util.Arrays;
import java.util.List;

public class StreamAnyMatchMethod {

	public static void main(String[] args) {

		// 1. list of 10 natural numbers
		List<Integer> numbers = Arrays
				.asList(1,2,3,4,5,6,7,8,9,10);

		// 1.1 predicate to find number greater than 9
		boolean bool1 = numbers
				.stream()
				.anyMatch(num -> num > 9);

		// 1.2 print to console
		System.out.println("Original list of integers : " + numbers);
		System.out.println("\nWhether integer list contains"
				+ " number greater than 9 = " + bool1);

		// 1.3 in line Predicate condition
		System.out.println("Whether integer list"
				+ " contains number greater than 10 = " 
				+ numbers.stream()
				.anyMatch(num -> num > 10));

		// 2. list of 5 Strings
		List<String> sectors = Arrays.asList(
				"Motor", 
				"Power", 
				"Steel", 
				"Chemicals", 
				"Capital"
				);

		// 2.1 predicate to find whether String element present or Not
		boolean bool2 = sectors
				.stream()
				.anyMatch(str -> str.contains("Power"));

		// 2.2 print to console
		System.out.println("\n\nOriginal list of Strings : " + sectors);
		System.out.println("\nWhether String list contains"
				+ " element 'Power' = " + bool2);

		// 2.3 in line Predicate condition
		System.out.println("Whether String list contains"
				+ " element 'Consumer' = " 
				+ sectors.stream()
				.anyMatch(str -> str.contains("Consumer")));
	}
}

Output:

Original list of integers : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Whether integer list contains number greater than 9 = true
Whether integer list contains number greater than 10 = false


Original list of Strings : [Motor, Power, Steel, Chemicals, Capital]

Whether String list contains element 'Power' = true
Whether String list contains element 'Consumer' = false

2.2 To find Student from multiple Predicates

  • A Student POJO is defined with 3 attributes
  • A list contains 5 Student objects defining their attributes like rollNumber, name, and age
  • We have defined 2 simple Predicate namely p1 and p2 and one more joined Predicate which is the combined Predicate of p1 && p2
  • 1st Predicate – find Student whose name starts with ‘K // returns true
  • 2nd Predicate – find Student with Age greater than 22 // returns true
  • 3rd Predicate – Student whose name starts with ‘K‘ and their Age is greater than 22 // returns false
  • inline Predicate – Student whose name starts with ‘V‘ and their Age is less than 18 // returns true

Student.java

package net.bench.resources.stream.anymatch.example;

public class Student {

	// member variables
	private int rollNumber;
	private String name;
	private int age;

	// constructors
	public Student(int rollId, String name, int age) {
		super();
		this.rollNumber = rollId;
		this.name = name;
		this.age = age;
	}

	// getters & setters
	public int getRollId() {
		return rollNumber;
	}
	public void setRollId(int rollId) {
		this.rollNumber = rollId;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}

	// toString()
	@Override
	public String toString() {
		return "Student [rollNumber=" + rollNumber 
				+ ", name=" + name 
				+ ", age=" + age 
				+ "]";
	}
}

StreamAnyMatchMethodForStudents.java

package net.bench.resources.stream.anymatch.example;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

import net.bench.resources.stream.min.max.example.Student;

public class StreamAnyMatchMethodForStudents {

	public static void main(String[] args) {

		// list of students
		List<Student> students = Arrays.asList(
				new Student(1, "Viraj", 17),
				new Student(2, "Krishnanand", 18),
				new Student(3, "Rishi", 16),
				new Student(4, "Suresh", 23),
				new Student(5, "Aditya", 21)
				);

		// predicate 1 - name starts with K
		Predicate<Student> p1 = stud -> stud.getName().startsWith("K");

		// predicate 2 - age older than 22
		Predicate<Student> p2 = stud -> stud.getAge() > 22;

		// combined predicate - p1 && p2
		Predicate<Student> p3 = p1.and(p2);

		// print all Students to console
		System.out.println("List of Students :-");
		students.stream().forEach(student -> System.out.println(student));

		// 1. find whether any Student name starts with 'K'
		boolean boolP1 = students.stream().anyMatch(p1);
		System.out.println("\n1. Whether Student whose name starts"
				+ " with 'K' present ? " + boolP1);

		// 2. find whether any Student name starts with 'K'
		boolean boolP2 = students.stream().anyMatch(p2);
		System.out.println("\n2. Student with Age greater"
				+ " than 22 present ? " + boolP2);

		// 3. Student Name starts with 'K' && Age greater than 22
		boolean boolP3 = students.stream().anyMatch(p3);
		System.out.println("\n3. Student Name starts with 'K' and"
				+ " Age greater than 22 present ? " + boolP3);

		// 4. in line multiple Predicate condition
		boolean boolP4 = students.stream().anyMatch(
				stud -> (stud.getName().startsWith("V") && stud.getAge() < 18));
		System.out.println("\n4. Student Name starts with 'V' "
				+ "and Age greater than 18 present ? " + boolP4);
	}
}

Output:

List of Students :-
Student [rollNumber=1, name=Viraj, age=17]
Student [rollNumber=2, name=Krishnanand, age=18]
Student [rollNumber=3, name=Rishi, age=16]
Student [rollNumber=4, name=Suresh, age=23]
Student [rollNumber=5, name=Aditya, age=21]

1. Whether Student whose name starts with 'K' present ? true

2. Student with Age greater than 22 present ? true

3. Student Name starts with 'K' and Age greater than 22 present ? false

4. Student Name starts with 'V' and Age greater than 18 present ? true

References:

Happy Coding !!
Happy Learning !!

Java 8 - Stream noneMatch() method with examples
Java 8 - Stream peek() method