Java Predicate and()

In this guide, you will learn about the Predicate and() method in Java programming and how to use it with an example.

1. Predicate and() Method Overview

Definition:

The Predicate.and() is a default method provided in the Predicate interface. It is used to combine two predicates using a logical AND operation. The result is a composite predicate that evaluates to true only if both the original and the specified predicate evaluate to true.

Syntax:

default Predicate<T> and(Predicate<? super T> other)

Parameters:

- other: A predicate which will be logically AND-ed with the current predicate.

Key Points:

- The and() method allows for the chaining of multiple predicate conditions.

- It's useful when multiple filtering conditions need to be applied to a data set.

- If either the current predicate or the specified predicate evaluates to false, the composite predicate will also evaluate to false.

2. Predicate and() Method Example

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

public class PredicateAndExample {
    public static void main(String[] args) {
        List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David", "Aria");

        // Define a Predicate to test if a name starts with the letter 'A'
        Predicate<String> startsWithA = name -> name.startsWith("A");
        // Define a Predicate to test if a name length is greater than 3
        Predicate<String> lengthGreaterThan3 = name -> name.length() > 3;

        // Combine the two predicates using and()
        Predicate<String> combinedPredicate = startsWithA.and(lengthGreaterThan3);

        for (String name : names) {
            if (combinedPredicate.test(name)) {
                System.out.println(name);
            }
        }
    }
}

Output:

Alice
Aria

Explanation:

In the provided example, we first define two separate predicates - one to check if a name starts with the letter 'A' and another to check if the length of the name is greater than 3. 

Using the and() method, these two predicates are combined to form a composite predicate. As a result, the names "Alice" and "Aria" from the list are printed, as they are the only names that satisfy both conditions.

Comments