In this tutorial we will see the example of Java 8 Stream anyMatch() method. This method returns true if any elements of the Stream matches the given predicate.
Lets see an example to understand the use of anyMatch() method.
Example: Java 8 Stream anyMatch() method
import java.util.List; import java.util.function.Predicate; import java.util.ArrayList; class Student{ int stuId; int stuAge; String stuName; Student(int id, int age, String name){ this.stuId = id; this.stuAge = age; this.stuName = name; } public int getStuId() { return stuId; } public int getStuAge() { return stuAge; } public String getStuName() { return stuName; } public static List<Student> getStudents(){ List<Student> list = new ArrayList<>(); list.add(new Student(11, 28, "Lucy")); list.add(new Student(28, 27, "Kiku")); list.add(new Student(32, 30, "Dani")); list.add(new Student(49, 27, "Steve")); return list; } } public class Example { public static void main(String[] args) { Predicate<Student> p1 = s -> s.stuName.startsWith("S"); Predicate<Student> p2 = s -> s.stuAge < 28 && s.stuName.startsWith("Z"); List<Student> list = Student.getStudents(); /* anyMatch() method checks whether any Stream element matches * the specified predicate */ boolean b3 = list.stream().anyMatch(p1); System.out.println(b3); boolean b4 = list.stream().anyMatch(p2); System.out.println(b4); } }
Output:
true false
In the above example we have two predicates, predicate p1 has condition that the student name starts with letter “S” and the predicate p2 has two conditions that the student name starts with letter “Z” and their age must be less than 28.
When we pass predicate as an argument to the anyMatch() method, it iterates over the elements of the stream to find the match. Since their is a match for predicate p1 (Student “Steve” name starts with “S”), it returns true, however none of the element matches predicate p2 so the anyMatch() method returns false for p2.
Leave a Reply