Saturday, 10 October 2020

Java Stream API: anyMatch(), allMatch(), and noneMatch() with Examples

          Java 8 introduced many powerful features, and the Stream API is one of the most important because it simplifies data processing and makes the code more concise and readable. In this post, we will explore the anyMatch(), allMatch(), and noneMatch() methods with examples.
  • anyMatch() – Returns true if at least one element in the stream matches the given predicate; otherwise, it returns false.

  • allMatch() – Returns true if all elements in the stream match the given predicate; otherwise, it returns false.

  • noneMatch() – Returns true if none of the elements in the stream match the given predicate; otherwise, it returns false.

Example:

package com.practice;

import java.util.ArrayList;
import java.util.List;

public class StreamMatchExample {

	public static void main(String[] args) {

		List<Employee> employeeList = new ArrayList<>();
		employeeList.add(new Employee("Mahesh", "Male", "abc@gmail.com"));
		employeeList.add(new Employee("Sathish", "Male", "abc@gmail.com"));
		employeeList.add(new Employee("Mahesh", "Male", "abc@gmail.com"));
		employeeList.add(new Employee("Pooja", "Female", "abc@gmail.com"));

		boolean allMatch = employeeList.stream().allMatch(
                               emp -> emp.getEmail().equalsIgnoreCase("abc@gmail.com"));
		System.out.println("allMatch - " + allMatch);

		boolean anyMatch = employeeList.stream().anyMatch(
                               emp -> emp.getName().equalsIgnoreCase("Mahesh"));
		System.out.println("anyMatch - " + anyMatch);

		boolean noneMatch = employeeList.stream().noneMatch(
                               emp -> emp.getName().equalsIgnoreCase("Anil"));
		System.out.println("noneMatch - " + noneMatch);
	}

}
 
Output :--
allMatch - true
anyMatch - true
noneMatch - true

Related Posts:-