How do I use the Predicate functional interface in Java?

The Predicate class in Java is a functional interface introduced in Java 8 under the java.util.function package. It is used to test a condition on an input and return a boolean value (true or false). Predicates are often used in lambda expressions or method references to filter data or apply conditional logic.

Here’s how we can use the Predicate class in Java:

Basic Predicate Usage

The Predicate interface has a single abstract method:

boolean test(T t);

We implement this method to provide our condition logic.

Example:

package org.kodejava.util.function;

import java.util.function.Predicate;

public class PredicateExample {
    public static void main(String[] args) {
        // Create a predicate that checks if a number is greater than 10
        Predicate<Integer> isGreaterThan10 = number -> number > 10;

        // Test the condition
        System.out.println(isGreaterThan10.test(15)); // Output: true
        System.out.println(isGreaterThan10.test(8));  // Output: false
    }
}

Chaining Predicates

Predicates provide methods to combine multiple conditions:
and() – Combines two predicates with logical AND.
or() – Combines two predicates with logical OR.
negate() – Negates the predicate (logical NOT).

Example:

package org.kodejava.util.function;

import java.util.function.Predicate;

public class PredicateChainingExample {
    public static void main(String[] args) {
        Predicate<Integer> isEven = number -> number % 2 == 0;
        Predicate<Integer> isGreaterThan5 = number -> number > 5;

        // Chain predicates
        Predicate<Integer> isEvenAndGreaterThan5 = isEven.and(isGreaterThan5);
        Predicate<Integer> isEvenOrGreaterThan5 = isEven.or(isGreaterThan5);

        // Test
        System.out.println(isEvenAndGreaterThan5.test(8));  // Output: true
        System.out.println(isEvenAndGreaterThan5.test(3));  // Output: false
        System.out.println(isEvenOrGreaterThan5.test(3));   // Output: false
        System.out.println(isEvenOrGreaterThan5.test(7));   // Output: true
    }
}

Using Predicate in Collections

The Predicate interface is extensively used in working with Streams or filtering collections.

Example:

package org.kodejava.util.function;

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

public class PredicateWithStreams {
    public static void main(String[] args) {
        List<String> names = Arrays.asList("Alice", "Bob", "Carol", "Mallory");

        // Create a predicate that tests if the string length is greater than 3
        Predicate<String> lengthGreaterThan3 = name -> name.length() > 3;

        // Filter and collect using the predicate
        List<String> filteredNames = names.stream()
                .filter(lengthGreaterThan3)
                .collect(Collectors.toList());

        // Output: [Alice, Carol, Mallory]
        System.out.println(filteredNames);
    }
}

Using Predicate with Default Methods

isEqual()

This static method evaluates if an object is equal to a predefined value.

Example:

package org.kodejava.util.function;

import java.util.function.Predicate;

public class PredicateIsEqualExample {
    public static void main(String[] args) {
        Predicate<String> isEqualToMark = Predicate.isEqual("Alice");

        // Output: true
        System.out.println(isEqualToMark.test("Alice"));
        // Output: false
        System.out.println(isEqualToMark.test("Bob"));
    }
}

Custom Predicate Usage

We can create our own predicate and pass it around in our code.

Example:

package org.kodejava.util.function;

import java.util.function.Predicate;

public class CustomPredicateExample {
    public static void main(String[] args) {
        // A custom method accepting a predicate
        testPredicate(value -> value > 10);

        // Another predicate for custom logic
        Predicate<Integer> isOdd = value -> value % 2 != 0;
        // Output: true
        System.out.println(isOdd.test(7));
    }

    static void testPredicate(Predicate<Integer> predicate) {
        // Output: true
        System.out.println(predicate.test(15));
    }
}

Summary

  • The Predicate interface is used for conditional checks and filtering data.
  • It works seamlessly with lambda expressions and method references.
  • You can combine multiple predicates using and, or, and negate.

This makes Predicate a very powerful and convenient tool for functional programming in Java!

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.