Java Predicate

Introduction

Java Predicate is one of the most commonly used Functional Interfaces introduced in Java 8 as part of the java.util.function package. It represents a function that takes one input argument and returns a boolean value (true or false). Predicates are primarily used for testing conditions, filtering data, validating inputs, and making logical decisions in Java applications.

Before Java 8, developers often created custom interfaces or anonymous classes to implement simple conditional checks. This resulted in more boilerplate code and reduced readability. With the introduction of Lambda Expressions, Method References, Streams, and Functional Interfaces, Java Predicate provides a concise and reusable way to express conditions.

For example, suppose you want to check whether a number is greater than 10.

Without Predicate:


public class Main {
    public static boolean isGreaterThanTen(int number) {
        return number > 10;
    }
    public static void main(String[] args) {
        System.out.println(isGreaterThanTen(15));
    }
}

Using Predicate:


import java.util.function.Predicate;
public class Main {
    public static void main(String[] args) {
        Predicate predicate = number -> number > 10;
        System.out.println(predicate.test(15));
    }
}

Output

true

The Predicate version is shorter, reusable, and integrates seamlessly with the Stream API.

In this tutorial, you’ll learn everything about Java Predicate, including syntax, methods, examples, real-life applications, advantages, limitations, common mistakes, best practices, and interview questions.

What is Java Predicate?

A Predicate is a Functional Interface that accepts one input argument and returns either true or false.

It is defined as:


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

Here:

  • T represents the input type.
  • test() evaluates a condition.
  • The return type is always boolean.

Predicates are commonly used for:

  • Filtering collections
  • Data validation
  • Searching records
  • Stream operations
  • Conditional processing

Why Do We Need Predicate?

Before Java 8:


public static boolean isEven(int number) {
    return number % 2 == 0;
}

With Predicate:


Predicate even = number -> number % 2 == 0;

Benefits include:

  • Less code
  • Better readability
  • Easy reuse
  • Works with Streams
  • Supports functional programming

Features of Predicate

Some important features are:

  • Introduced in Java 8
  • Part of java.util.function
  • Functional Interface
  • Accepts one parameter
  • Returns boolean
  • Works with Lambda Expressions
  • Supports Method References
  • Integrates with Stream API
  • Provides logical operations
  • Improves code readability

Syntax


Predicate predicate = parameter -> condition;

Example:


Predicate isEmpty = text -> text.isEmpty();

Testing the predicate:


System.out.println(isEmpty.test(""));

Output

true

The test() Method

The primary method of Predicate is:


boolean test(T t)

Example:


import java.util.function.Predicate;
public class Main {
    public static void main(String[] args) {
        Predicate even = number -> number % 2 == 0;
        System.out.println(even.test(8));
    }
}

Output

true

Example 1: Check Positive Number


import java.util.function.Predicate;
public class Main {
    public static void main(String[] args) {
        Predicate positive = number -> number > 0;
        System.out.println(positive.test(20));
        System.out.println(positive.test(-5));
    }
}

Output

true
false

Example 2: Check String Length


import java.util.function.Predicate;
public class Main {
    public static void main(String[] args) {
        Predicate longString =
                text -> text.length() > 5;
        System.out.println(longString.test("Java"));
        System.out.println(longString.test("Programming"));
    }
}

Output

false
true

Example 3: Check Even Number


import java.util.function.Predicate;
public class Main {
    public static void main(String[] args) {
        Predicate even = n -> n % 2 == 0;
        System.out.println(even.test(18));
    }
}

Output

true

Predicate with Stream API

Predicate is frequently used with the Stream API for filtering.

Example:


import java.util.*;
import java.util.function.Predicate;
public class Main {
    public static void main(String[] args) {
        List numbers =
                Arrays.asList(10, 15, 20, 25, 30);
        Predicate even = n -> n % 2 == 0;
        numbers.stream()
                .filter(even)
                .forEach(System.out::println);
    }
}

Output

10
20
30

Predicate Methods

Besides test(), Predicate provides several default methods.

Method Description
test() Evaluates the condition
and() Logical AND
or() Logical OR
negate() Logical NOT
isEqual() Checks equality

Using and()


Predicate greaterThan10 = n -> n > 10;
Predicate lessThan50 = n -> n < 50;
Predicate result =
        greaterThan10.and(lessThan50);
System.out.println(result.test(30));

Output

true

Using or()


Predicate lessThan5 = n -> n < 5;
Predicate greaterThan100 = n -> n > 100;
Predicate result =
        lessThan5.or(greaterThan100);
System.out.println(result.test(3));

Output

true

Using negate()


Predicate even = n -> n % 2 == 0;
Predicate odd = even.negate();
System.out.println(odd.test(7));

Output

true

Using isEqual()


Predicate predicate =
        Predicate.isEqual("Java");
System.out.println(predicate.test("Java"));

Output

true

Predicate vs Function

Predicate Function
Returns boolean Returns any type
Used for conditions Used for transformations
Method: test() Method: apply()
Filtering Data conversion

Predicate vs Function

Predicate Consumer
Returns boolean Returns nothing
Checks condition Performs action
Uses test() Uses accept()

Real-life Example

Imagine an Employee Management System where only employees with a salary greater than ₹50,000 should be displayed.


class Employee {
    String name;
    int salary;
    Employee(String name, int salary) {
        this.name = name;
        this.salary = salary;
    }
}

Predicate:


Predicate highSalary =
        employee -> employee.salary > 50000;

This predicate can be used with streams:


employees.stream()
         .filter(highSalary)
         .forEach(employee ->
                 System.out.println(employee.name));

Other real-world applications include:

  • User authentication
  • Form validation
  • Product filtering
  • Banking eligibility
  • Loan approval
  • Student grading
  • Order processing
  • Inventory management

Advantages of Predicate

  • Reduces boilerplate code
  • Easy to understand
  • Reusable logic
  • Supports lambda expressions
  • Integrates with Stream API
  • Improves readability
  • Supports logical composition
  • Encourages functional programming

Limitations

  • Accepts only one input parameter.
  • Returns only a boolean value.
  • Not suitable for data transformation (use Function instead).
  • Complex conditions can reduce readability if written in a single lambda.

Common Mistakes

1. Forgetting to Call test()

Incorrect:


Predicate even = n -> n % 2 == 0;
System.out.println(even);

Correct:


System.out.println(even.test(10));

2. Returning Non-Boolean Values

Incorrect:


Predicate predicate =
        number -> number + 5;

A Predicate must always return a boolean.

Correct:


Predicate predicate =
        number -> number > 5;

3. Using Predicate for Data Transformation

Incorrect:


Predicate predicate =
        text -> text.toUpperCase();

Use a Function for transforming data instead.

4. Ignoring Built-in Methods

Instead of writing complex nested conditions, use and(), or(), and negate() to improve readability.

5. Writing Overly Complex Lambdas

Keep Predicate expressions simple and focused on a single condition whenever possible.

Best Practices

  • Use Predicate only for boolean conditions.
  • Keep predicate logic concise.
  • Reuse predicates instead of duplicating conditions.
  • Use and(), or(), and negate() for combining conditions.
  • Prefer meaningful variable names such as isAdult, isEligible, or hasPermission.
  • Combine Predicate with the Stream API for filtering collections.
  • Use Method References where applicable.

Time Complexity

Predicate evaluation is generally constant time, but the overall complexity depends on how it is used.

Operation Time Complexity
test() O(1)
and() O(1)
or() O(1)
negate() O(1)
filter() on Stream O(n)

Conclusion

Java Predicate is a powerful Functional Interface introduced in Java 8 that simplifies conditional logic by representing boolean-valued functions. It plays a key role in modern Java programming, particularly when working with Lambda Expressions, Method References, and the Stream API. By using Predicate, developers can write cleaner, more reusable, and more expressive code for validation, filtering, and decision-making.

Understanding Predicate, its methods (test(), and(), or(), negate(), and isEqual()), best practices, and real-world applications will help you build maintainable Java applications and prepare effectively for Java interviews. It is one of the foundational functional interfaces that every Java developer should master.

Related Java Tutorials