Java 8 Stream: allMatch, anyMatch and noneMatch Example
November 18, 2014
Java 8 Stream allMatch, anyMatch and noneMatch methods are applied on stream object that matches the given Predicate and then returns boolean value. allMatch()
checks if calling stream totally matches to given Predicate
, if yes it returns true otherwise false. anyMatch()
checks if there is any element in the stream which matches the given Predicate
. noneMatch()
returns true only when no element matches the given Predicate
.
Stream.allMatch
We passPredicate
as an argument to allMatch()
method. That Predicate
is applied to each element of stream and if each and every element satisfies the given Predicate
then it returns true otherwise false.
Stream.anyMatch
ForanyMatch()
method we pass Predicate
as an argument. The element of stream is iterated for this Predicate
. If any element matches then it returns true otherwise false.
Stream.noneMatch
noneMatch()
method is a method which takes argument as a Predicate
and if none of element of stream matches the given Predicate
, then it returns true otherwise false.
Now find the example for all the three methods
allMatch()
, anyMatch()
and noneMatch()
.
MatchDemo.java
package com.concretepage.util.stream; import java.util.List; import java.util.function.Predicate; public class MatchDemo { public static void main(String[] args) { Predicate<Employee> p1 = e -> e.id < 10 && e.name.startsWith("A"); Predicate<Employee> p2 = e -> e.sal < 10000; List<Employee> list = Employee.getEmpList(); //using allMatch boolean b1 = list.stream().allMatch(p1); System.out.println(b1); boolean b2 = list.stream().allMatch(p2); System.out.println(b2); //using anyMatch boolean b3 = list.stream().anyMatch(p1); System.out.println(b3); boolean b4 = list.stream().anyMatch(p2); System.out.println(b4); //using noneMatch boolean b5 = list.stream().noneMatch(p1); System.out.println(b5); } }
Employee
class.
Employee.java
package com.concretepage.util.stream; import java.util.ArrayList; import java.util.List; public class Employee { public int id; public String name; public int sal; public Employee(int id,String name,int sal ){ this.id = id; this.name = name; this.sal = sal; } public static List<Employee> getEmpList(){ List<Employee> list = new ArrayList<>(); list.add(new Employee(1, "A", 2000)); list.add(new Employee(2, "B", 3000)); list.add(new Employee(3, "C", 4000)); list.add(new Employee(4, "D", 5000)); return list; } }
false true true true false