Java examples of chained predicates and to perform ‘logical AND‘ and ‘logical OR‘ operations and collect the elements into a list.
1. Predicate.and() – Logical AND example
In given example, we have used Predicate.and() method which returns a composed predicate that represents a short-circuiting logical AND of this predicate and another.
When evaluating the composed predicate, if first predicate is
false
, then the other predicate is not evaluated.
Any exceptions thrown during evaluation of either predicate are relayed to the caller; if evaluation of first predicate throws an exception, the other predicate will not be evaluated.
import java.util.Arrays; import java.util.List; import java.util.function.Predicate; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { List<Employee> employeesList = Arrays.asList( new Employee(1, "Alex", 100), new Employee(2, "Brian", 200), new Employee(3, "Charles", 300), new Employee(4, "David", 400), new Employee(5, "Edward", 500), new Employee(6, "Frank", 600) ); Predicate<Employee> idLessThan4 = e -> e.getId() < 4; Predicate<Employee> salaryGreaterThan200 = e -> e.getSalary() > 200; List<Employee> filteredEmployees = employeesList.stream() .filter( idLessThan4.and( salaryGreaterThan200 ) ) .collect(Collectors.toList()); System.out.println(filteredEmployees); } }
Program output.
[Employee [id=3, name=Charles, salary=300.0]]
2. Predicate.or() – Logical OR example
In given example, we have used Predicate.or() method which returns a composed predicate that represents a short-circuiting logical OR of given predicate and another predicate.
When evaluating the composed predicate, if first predicate is
true
, then the other predicate is not evaluated.
Any exceptions thrown during evaluation of either predicate are relayed to the caller; if evaluation of first predicate throws an exception, the other predicate will not be evaluated.
import java.util.Arrays; import java.util.List; import java.util.function.Predicate; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { List<Employee> employeesList = Arrays.asList( new Employee(1, "Alex", 100), new Employee(2, "Brian", 200), new Employee(3, "Charles", 300), new Employee(4, "David", 400), new Employee(5, "Edward", 500), new Employee(6, "Frank", 600) ); Predicate<Employee> idLessThan2 = e -> e.getId() < 2; Predicate<Employee> salaryGreaterThan500 = e -> e.getSalary() > 500; List<Employee> filteredEmployees = employeesList.stream() .filter( idLessThan2.or( salaryGreaterThan500 ) ) .collect(Collectors.toList()); System.out.println(filteredEmployees); } }
Program output.
[Employee [id=1, name=Alex, salary=100.0], Employee [id=6, name=Frank, salary=600.0]]
Drop me your questions related to Java stream chained predicates equivalent to logical operators between predicates.
Happy Learning !!
Leave a Reply