Course contentsShow
← Java
Lesson 1643 of 2,87035. Functional InterfacesFree lesson

The isEqual Static Method for Equality Testing

Use Predicate.isEqual(targetRef) to create predicates that test object equality, handling null references safely.

The isEqual Static Method for Equality Testing

You'll learn how to create safe, null-tolerant equality predicates using a built-in factory method.

The Core Idea

Java's Predicate interface includes a static factory method called isEqual() that creates a predicate specifically for testing object equality. Instead of writing x -> x.equals(targetValue) (which can throw NullPointerException), you can use Predicate.isEqual(targetValue) to get a predicate that safely handles null references.

Think of it like a protective wrapper around equality testing—it checks "is this object equal to my target?" while gracefully handling cases where either value might be null.

How It Works

The isEqual() method takes a target reference and returns a Predicate<T> that tests if its input equals that target. The implementation uses Objects.equals() internally, which means:

  • If both the target and test value are null, the result is true
  • If one is null and the other isn't, the result is false
  • Otherwise, it delegates to the equals() method
// Create a predicate that tests equality to "Java"
Predicate<String> isJava = Predicate.isEqual("Java");

// Use it to test values
boolean result1 = isJava.test("Java");    // true
boolean result2 = isJava.test("Python");  // false
boolean result3 = isJava.test(null);      // false

// With a null target
Predicate<String> isNull = Predicate.isEqual(null);
boolean result4 = isNull.test(null);      // true
boolean result5 = isNull.test("Java");    // false

This is particularly useful when filtering collections or combining with other predicates using and(), or(), and negate().

Key Takeaway: Predicate.isEqual(targetRef) provides a concise, null-safe way to create equality-testing predicates without writing custom lambda expressions or risking null pointer exceptions.