o7planning

Java Predicate Tutorial

View more Tutorials:

1- Predicate

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));
    }
}
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
  • TODO Link!
  • TODO Link!
  • TODO Link!
  • TODO Link!

2- Predicate + Method reference

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()

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(..)

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(..)

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(..)

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

View more Tutorials:

Maybe you are interested

These are online courses outside the o7planning website that we introduced, which may include free or discounted courses.