Java Predicate Tutorial with Examples
1. Predicate
No ADS
In Java 8, Predicate is a functional interface, representing an operator that accepts an input parameter and returns a boolean value.
Predicate
@FunctionalInterface
public interface Predicate<T> {
boolean test(T t);
}
Example: Create a Predicate to check if a number is odd or not.
PredicateEx1.java
package org.o7planning.ex;
import java.util.function.Predicate;
public class PredicateEx1 {
public static void main(String[] args) {
Predicate<Integer> tester = value -> value % 2 == 1;
int value = 11;
System.out.println(value + " Is an Odd Number? " + tester.test(value));
}
}
Output:
11 Is an Odd Number? true
Predicate is also used to check whether the elements in a list match a certain condition.
Example: A list of Integer numbers, we will filter out a new list consisting of only odd numbers.
PredicateEx2.java
package org.o7planning.ex;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class PredicateEx2 {
public static void main(String[] args) {
Predicate<Integer> tester = value -> value % 2 == 1;
List<Integer> list = Arrays.asList(10, 11, 13, 14, 15, 16, 17);
// @see: stream.filter(Predicate)
List<Integer> newList = list.stream() //
.filter(tester).collect(Collectors.toList());
// @see: list.forEach(Consumer)
newList.forEach(System.out::println);
}
}
Output:
11
13
15
17
Example: From a list of names, print only those whose names begin with "S":
PredicateEx3.java
package org.o7planning.ex;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
public class PredicateEx3 {
public static void main(String[] args) {
Predicate<String> tester = name -> name.startsWith("S");
List<String> names = Arrays.asList("John", "Smith", "Samueal", "Catley", "Sie");
// @see: stream.filter(Predicate)
// @see: stream.forEach(Consumer)
names.stream().filter(tester).forEach(System.out::println);
}
}
Output:
Smith
Samueal
Sie
- BiPredicate
- IntPredicate
- LongPredicate
- DoublePredicate
- Supplier
- Consumer
- BiConsumer
- Function
- BiFunction
2. Predicate + Method reference
No ADS
Next, we come to examples of creating a Predicate from a method reference. Employee and EmployeeUtils classes participate in these examples.
Employee.java
package org.o7planning.ex;
public class Employee {
private String name;
private float salary;
private String gender; // "M", "F"
public Employee(String name, float salary, String gender) {
this.name = name;
this.salary = salary;
this.gender = gender;
}
public String getName() {
return name;
}
public float getSalary() {
return salary;
}
public String getGender() {
return gender;
}
public boolean isFemale() {
return "F".equals(this.getGender());
}
}
EmployeeUtils.java
package org.o7planning.ex;
public class EmployeeUtils {
public static boolean isHighSalary(Employee e) {
return e.getSalary() > 5000;
}
}
M.ref Example 1:
If a static method takes a parameter of type <T> and returns a boolean, then its reference can be considered a Predicate<T>:
Example: The static method EmployeeUtils.isHighSalary(Employee) is a Predicate<Employee>:
Predicate<Employee> p = EmployeeUtils::isHighSalary;
// Same as:
Predicate<Employee> p = employee -> EmployeeUtils.isHighSalary(employee);
Predicate_mr_ex1.java
package org.o7planning.ex;
import java.util.function.Predicate;
public class Predicate_mr_ex1 {
public static void main(String[] args) {
Employee sophia = new Employee("Sophia B.", 7000, "F");
// Create a Predicate from a method reference.
Predicate<Employee> tester = EmployeeUtils::isHighSalary;
System.out.println("High Salary? " + tester.test(sophia));
}
}
Output:
High Salary? true
M.ref Example 2:
Employee.isFemale() is a non-static method, no parameter and returns a boolean, so its reference is considered a Predicate<Employee>:
Predicate<Employee> p = Employee::isFemale;
// Same as:
Predicate<Employee> p = employee -> employee.isFemale();
Predicate_mr_ex2.java
package org.o7planning.ex;
import java.util.function.Predicate;
public class Predicate_mr_ex2 {
public static void main(String[] args) {
Employee sophia = new Employee("Sophia B.", 7000, "F");
// Create a Predicate from a method reference.
Predicate<Employee> tester = Employee::isFemale;
System.out.println("High Salary? " + tester.test(sophia));
}
}
Output:
High Salary? true
3. negate()
No ADS
negate() method returns a new Predicate object, whose evaluation is a negative of the current Predicate.
default Predicate<T> negate() {
return (t) -> !test(t);
}
Example: A list of Integer numbers, we will filter out a new list containing only even numbers.
PredicateEx7.java
package org.o7planning.ex;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class PredicateEx7 {
public static void main(String[] args) {
// Checks if a number is odd.
Predicate<Integer> tester = value -> value % 2 == 1;
List<Integer> list = Arrays.asList(10, 11, 13, 14, 15, 16, 17);
// @see: stream.filter(Predicate)
List<Integer> newList = list.stream() //
.filter(tester.negate()).collect(Collectors.toList());
// @see: list.forEach(Consumer)
newList.forEach(System.out::println);
}
}
Output:
10
14
16
4. and(Predicate other)
No ADS
and(other) method creates a new Predicate object by combining the current Predicate object and other. It evaluates true if both current Predicate and other evaluate to true.
default Predicate<T> and(Predicate<? super T> other) {
Objects.requireNonNull(other);
return (t) -> test(t) && other.test(t);
}
Example: A list of Integer numbers, we will filter out a new list consisting of only odd numbers and greater than 20.
PredicateEx8.java
package org.o7planning.ex;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class PredicateEx8 {
public static void main(String[] args) {
// Test if a number is odd.
Predicate<Integer> tester1 = value -> value % 2 == 1;
// Test if anumber > 20
Predicate<Integer> tester2 = value -> value > 20;
List<Integer> list = Arrays.asList(10, 11, 13, 14, 15, 16, 17, 25, 27, 26, 28);
// A List of odd and greater than 20.
// @see: stream.filter(Predicate)
List<Integer> newList = list.stream() //
.filter(tester1.and(tester2)).collect(Collectors.toList());
// @see: list.forEach(Consumer)
newList.forEach(System.out::println);
}
}
Output:
25
27
5. or(Predicate other)
or(other) method returns a new Predicate object by combining the current Predicate object and other. It evaluates true if either current Predicate or other evaluates to true.
default Predicate<T> or(Predicate<? super T> other) {
Objects.requireNonNull(other);
return (t) -> test(t) || other.test(t);
}
Example: Give a list of names, print out names beginning with "A" or ending with "p".
PredicateEx9.java
package org.o7planning.ex;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
public class PredicateEx9 {
public static void main(String[] args) {
List<String> names = Arrays.asList("Peter", "Martin", "Alex", "Philip", "Piyush", "Mike");
Predicate<String> tester1 = name -> name.startsWith("A");
Predicate<String> tester2 = name -> name.endsWith("p");
// find a name starts with "A" or ends with "p"
names.stream().filter(tester1.or(tester2)).forEach(System.out::println);
}
}
Output:
Alex
Philip
6. isEqual(Object targetRef)
No ADS
Static method Predicate.isEqual(targetRef) returns a Predicate to check whether two objects are equal or not using Objects.equals(Object,Object) method.
static <T> Predicate<T> isEqual(Object targetRef) {
return (null == targetRef)
? Objects::isNull
: object -> targetRef.equals(object);
}
PredicateEx10.java
package org.o7planning.ex;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.function.Predicate;
public class PredicateEx10 {
public static void main(String[] args) {
Predicate<String> test1 = Predicate.isEqual("Mike");
// test1 same as test2:
Predicate<String> test2 = myIsEqual("Mike");
List<String> names = Arrays.asList(
"Peter",
"Martin",
"Alex",
"Philip",
"Piyush",
"Mike"
);
// Find a name that is equals "Mike"
names.stream()
.filter(test1)
.forEach(System.out::println);
}
public static <T> Predicate<T> myIsEqual(Object targetRef) {
Predicate<T> tester = obj -> Objects.equals(obj, targetRef);
return tester;
}
}
Output:
Mike
No ADS
Java Basic
- Data Types in java
- Java PhantomReference Tutorial with Examples
- JDK Javadoc in CHM format
- Java Stream Tutorial with Examples
- Java Predicate Tutorial with Examples
- Java BiConsumer Tutorial with Examples
- Arrays in Java
- JDBC Driver Libraries for different types of database in Java
- Abstract class and Interface in Java
- Java Commons Email Tutorial with Examples
- Install Eclipse
- Bitwise Operations
- Install Eclipse on Ubuntu
- Configuring Eclipse to use the JDK instead of JRE
- Java Commons Logging Tutorial with Examples
- Java Enums Tutorial with Examples
- Loops in Java
- Java Regular Expressions Tutorial with Examples
- Install Java on Ubuntu
- Quick Learning Java for beginners
- Install Java on Windows
- Comparing and Sorting in Java
- Inheritance and polymorphism in Java
- Java Consumer Tutorial with Examples
- Java String, StringBuffer and StringBuilder Tutorial with Examples
- Java Exception Handling Tutorial with Examples
- Example of Java encoding and decoding using Apache Base64
- if else statement in java
- Switch Statement in Java
- Java Supplier Tutorial with Examples
- Java Programming for team using Eclipse and SVN
- Java JDBC Tutorial with Examples
- Java remote method invocation - Java RMI Tutorial with Examples
- Java Multithreading Programming Tutorial with Examples
- Customize java compiler processing your Annotation (Annotation Processing Tool)
- What is needed to get started with Java?
- Java Aspect Oriented Programming with AspectJ (AOP)
- Understanding Java System.identityHashCode, Object.hashCode and Object.equals
- Java Compression and Decompression Tutorial with Examples
- Java Reflection Tutorial with Examples
- Install OpenJDK on Ubuntu
- Java String.format() and printf() methods
- History of Java and the difference between Oracle JDK and OpenJDK
- Introduction to the Raspberry Pi
- Java Socket Programming Tutorial with Examples
- Java Generics Tutorial with Examples
- Manipulating files and directories in Java
- Java WeakReference Tutorial with Examples
- Java Commons IO Tutorial with Examples
- History of bits and bytes in computer science
- Which Platform Should You Choose for Developing Java Desktop Applications?
- Java SoftReference Tutorial with Examples
- Syntax and new features in Java 8
- Java Annotations Tutorial with Examples
- Java Function Tutorial with Examples
- Access modifiers in Java
- Java BiFunction Tutorial with Examples
- Get the values of the columns automatically increment when Insert a record using JDBC
- Java Functional Interface Tutorial with Examples
- Java BiPredicate Tutorial with Examples
Show More
- Java Servlet/Jsp Tutorials
- Java Collections Framework Tutorials
- Java API for HTML & XML
- Java IO Tutorials
- Java Date Time Tutorials
- Spring Boot Tutorials
- Maven Tutorials
- Gradle Tutorials
- Java Web Services Tutorials
- Java SWT Tutorials
- JavaFX Tutorials
- Java Oracle ADF Tutorials
- Struts2 Framework Tutorials
- Spring Cloud Tutorials