Java 8 Predicate examples

In Java 8, the Predicate interface is a functional interface that represents a single argument function that returns a boolean value. It is a part of the java.util.function package and is often used to define conditions or filters on data. In this post, we are going to see Java 8 Predicate examples.

The Predicate interface has an abstract method called test(T t), where T is the type of input argument. The test() method takes an input of type T and returns true or false based on whether the condition defined by the Predicate is satisfied for the input value.

Here’s the basic structure of the Predicate interface.

@FunctionalInterface
public interface Predicate<T> {
    boolean test(T t);
}

Now, let’s look at an example to understand how to use Predicate in Java 8:

Suppose you have a list of integers and you want to filter out the even numbers from the list using a Predicate.

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

public class PredicateExample {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

        // Define a Predicate to filter even numbers
        Predicate<Integer> evenPredicate = number -> number % 2 == 0;

        // Use the Predicate to filter even numbers
        numbers.stream()
               .filter(evenPredicate)
               .forEach(System.out::println);
    }
}

In this example, we create a Predicate evenPredicate that tests whether a given number is even or not. We then use the filter method of the Stream API to filter out the even numbers from the list of integers. Finally, we use the forEach method to print out the filtered even numbers.

Output:-

2
4
6
8
10

Predicate and(), or() and negate() Example

package com.javatute.java8;

import java.util.function.Predicate;

public class PredicateOrAndExample {
    public static void main(String[] args) {
        int[] numbers = {10, 20, 30, 2, 3, 9, 5, 14, 60};
        Predicate<Integer> p1 = n -> n % 2 == 0;
        Predicate<Integer> p2 = n -> n > 20;

        for (Integer i : numbers) {
            if (p1.and(p2).test(i)) {
                System.out.println("Predicate and() example "+i);
            }
        }

        for (Integer i : numbers) {
            if (p1.or(p2).test(i)) {
                System.out.println("Predicate or() example "+i);
            }
        }

        for (Integer i : numbers) {
            if (p2.negate().test(i)) {
                System.out.println("Predicate negate() example "+i);
            }
        }
    }
}

Output:-

Predicate and() example 30
Predicate and() example 60
Predicate or() example 10
Predicate or() example 20
Predicate or() example 30
Predicate or() example 2
Predicate or() example 14
Predicate or() example 60
Predicate negate() example 10
Predicate negate() example 20
Predicate negate() example 2
Predicate negate() example 3
Predicate negate() example 9
Predicate negate() example 5
Predicate negate() example 14

Let’s see some more Java 8 Predicate examples.

1. Employee Filtering: Suppose you have a list of employees and you want to filter out employees who earn more than a certain salary threshold.

import java.util.List;
import java.util.function.Predicate;

public class EmployeeFilterExample {
    public static void main(String[] args) {
        List<Employee> employees = // initialize the list with employee objects

        Predicate<Employee> salaryPredicate = employee -> employee.getSalary() > 50000;

        List<Employee> highPaidEmployees = employees.stream()
                .filter(salaryPredicate)
                .collect(Collectors.toList());
    }
}

2. Password Strength Validation.

You want to validate passwords based on certain criteria like minimum length, containing uppercase and lowercase letters, numbers, and special characters.

import java.util.function.Predicate;

public class PasswordValidationExample {
    public static void main(String[] args) {
        String password = // get password from user input

        Predicate<String> passwordValidator = p -> p.length() >= 8 &&
                p.matches(".*[a-z].*") &&
                p.matches(".*[A-Z].*") &&
                p.matches(".*\\d.*") &&
                p.matches(".*[@#$%^&+=].*");

        boolean isValid = passwordValidator.test(password);
    }
}

3. List Element Validation: You have a list of strings and you want to filter out strings that are shorter than a specified length.

import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class ListElementValidationExample {
    public static void main(String[] args) {
        List<String> words = // initialize the list with strings

        int minLength = 5;
        Predicate<String> lengthPredicate = word -> word.length() >= minLength;

        List<String> filteredWords = words.stream()
                .filter(lengthPredicate)
                .collect(Collectors.toList());
    }
}

4. Product Discount Calculation: You have a list of products and you want to apply a discount to products that belong to a certain category.

import java.util.List;
import java.util.function.Predicate;

public class ProductDiscountExample {
    public static void main(String[] args) {
        List<Product> products = // initialize the list with product objects

        Predicate<Product> categoryPredicate = product -> product.getCategory().equals("Electronics");

        products.forEach(product -> {
            if (categoryPredicate.test(product)) {
                product.applyDiscount(10); // Apply a 10% discount to Electronics category products
            }
        });
    }
}

5. Age Group Classification: You have a list of people with their ages, and you want to classify them into different age groups.

import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class AgeGroupClassificationExample {
    public static void main(String[] args) {
        List<Person> people = // initialize the list with person objects

        Predicate<Person> youngPredicate = person -> person.getAge() < 30;
        Predicate<Person> middleAgedPredicate = person -> person.getAge() >= 30 && person.getAge() < 60;
        Predicate<Person> seniorPredicate = person -> person.getAge() >= 60;

        List<Person> youngPeople = people.stream()
                .filter(youngPredicate)
                .collect(Collectors.toList());

        List<Person> middleAgedPeople = people.stream()
                .filter(middleAgedPredicate)
                .collect(Collectors.toList());

        List<Person> seniorPeople = people.stream()
                .filter(seniorPredicate)
                .collect(Collectors.toList());
    }
}

These examples demonstrate how the Predicate interface can be used in various real-time scenarios to define conditions, filters, and validations. It provides a flexible way to implement conditional logic in a functional programming style.

Let’s see a few questions related to Java 8 Predicate functional interface.

Question 1:
What is the purpose of the Java 8 Predicate functional interface?
A) It represents a boolean-valued function that takes an object as input and returns a boolean result.
B) It represents a single abstract method interface used for sorting collections.
C) It is used to define methods for converting objects to strings.
D) It is used for creating parallel streams in Java.

Question 2:
Which method is used to test an object using a Predicate?
A) boolean test(Object obj)
B) boolean apply(Object obj)
C) boolean check(Object obj)
D) boolean evaluate(Object obj)

Question 3:
How is a Predicate typically used with Java collections?
A) To modify elements of the collection.
B) To filter elements based on a specified condition.
C) To sort elements using a custom comparator.
D) To add new elements to the collection.

Question 4:
Which of the following represents a valid way to create a Predicate using a lambda expression?
A) Predicate<Integer> p = (x) -> x > 10;
B) Predicate<String> p = (s) -> s.length() < 5;
C) Predicate<Double> p = (num) => num >= 0.0;
D) Predicate<Boolean> p = (b) -> !b;

Question 5:
What is the return type of the test method in the Predicate interface?
A) void
B) Object
C) boolean
D) int

Answers:

  1. A) It represents a boolean-valued function that takes an object as input and returns a boolean result.
  2. A) boolean test(Object obj)
  3. B) To filter elements based on a specified condition.
  4. A) Predicate<Integer> p = (x) -> x > 10;
  5. C) boolean

Summary – The Predicate interface provides a convenient way to define conditions or filters that can be used in various scenarios, such as filtering collections, validating data, and more. It’s a powerful tool for working with functional programming concepts in Java.

See docs.

Other Java 8 tutorial.

That’s all about Java 8 Predicate examples.