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()– Returnstrueif at least one element in the stream matches the given predicate; otherwise, it returnsfalse.allMatch()– Returnstrueif all elements in the stream match the given predicate; otherwise, it returnsfalse.noneMatch()– Returnstrueif none of the elements in the stream match the given predicate; otherwise, it returnsfalse.
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:-