Java Predicate

Introduction

In Java, the Predicate interface is a functional interface that represents a predicate (boolean-valued function) of one argument. It is part of the java.util.function package and is commonly used for evaluating conditions and filtering data.

Table of Contents

  1. What is Predicate?
  2. Methods and Syntax
  3. Examples of Predicate
  4. Real-World Use Case
  5. Conclusion

1. What is Predicate?

Predicate is a functional interface that accepts one argument and returns a boolean result. It is useful for scenarios where a condition needs to be checked or data needs to be filtered based on a criterion.

2. Methods and Syntax

The main methods in the Predicate interface are:

  • boolean test(T t): Evaluates this predicate on the given argument.
  • default Predicate<T> and(Predicate<? super T> other): Returns a composed predicate that represents a short-circuiting logical AND of this predicate and another.
  • default Predicate<T> or(Predicate<? super T> other): Returns a composed predicate that represents a short-circuiting logical OR of this predicate and another.
  • default Predicate<T> negate(): Returns a predicate that represents the logical negation of this predicate.

Syntax

Predicate<T> predicate = (T t) -> {
    // condition on t
    return result;
};

3. Examples of Predicate

Example 1: Checking if a String is Empty

import java.util.function.Predicate;

public class IsEmptyExample {
    public static void main(String[] args) {
        // Define a Predicate that checks if a string is empty
        Predicate<String> isEmpty = (str) -> str.isEmpty();

        boolean result = isEmpty.test("");
        System.out.println("Is empty? " + result);
    }
}

Output:

Is empty? true

Example 2: Using and

import java.util.function.Predicate;

public class AndExample {
    public static void main(String[] args) {
        // Define predicates for checking if a string is not empty and has more than 5 characters
        Predicate<String> isNotEmpty = (str) -> !str.isEmpty();
        Predicate<String> hasMoreThanFiveChars = (str) -> str.length() > 5;

        Predicate<String> isValid = isNotEmpty.and(hasMoreThanFiveChars);

        boolean result = isValid.test("HelloWorld");
        System.out.println("Is valid? " + result);
    }
}

Output:

Is valid? true

Example 3: Using or

import java.util.function.Predicate;

public class OrExample {
    public static void main(String[] args) {
        // Define predicates for checking if a string is empty or has more than 5 characters
        Predicate<String> isEmpty = (str) -> str.isEmpty();
        Predicate<String> hasMoreThanFiveChars = (str) -> str.length() > 5;

        Predicate<String> isEither = isEmpty.or(hasMoreThanFiveChars);

        boolean result = isEither.test("Hello");
        System.out.println("Is either? " + result);
    }
}

Output:

Is either? false

Example 4: Using negate

import java.util.function.Predicate;

public class NegateExample {
    public static void main(String[] args) {
        // Define a predicate for checking if a string is empty
        Predicate<String> isEmpty = (str) -> str.isEmpty();

        Predicate<String> isNotEmpty = isEmpty.negate();

        boolean result = isNotEmpty.test("Hello");
        System.out.println("Is not empty? " + result);
    }
}

Output:

Is not empty? true

4. Real-World Use Case: Filtering a List of Strings

In applications, Predicate can be used to filter a list of strings based on certain criteria.

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

public class FilterStrings {
    public static void main(String[] args) {
        List<String> strings = List.of("Apple", "Banana", "Cherry", "Date", "Fig");

        // Define a Predicate to filter strings that start with 'B'
        Predicate<String> startsWithB = (str) -> str.startsWith("B");

        List<String> filteredStrings = strings.stream()
                .filter(startsWithB)
                .collect(Collectors.toList());

        System.out.println("Filtered strings: " + filteredStrings);
    }
}

Output:

Filtered strings: [Banana]

Conclusion

The Predicate interface is used in Java for evaluating conditions involving objects. It simplifies filtering and logical operations, enhancing code clarity and maintainability. Using Predicate can lead to cleaner and more efficient code, especially in functional programming contexts.

Comments