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

Creating Simple Predicates with Lambda Expressions

Write basic predicates using lambda syntax to test conditions like value ranges, null checks, and property validation.

Creating Simple Predicates with Lambda Expressions

You'll learn how to write concise lambda expressions that test conditions using the Predicate<T> functional interface.

What You're Building

Now that you understand Predicate<T> and its test method, it's time to create your own predicates using lambda syntax. Instead of writing full anonymous class implementations, lambdas let you express test conditions in a clean, readable way.

Core Syntax

A lambda predicate follows this pattern:

Predicate<Type> name = (parameter) -> boolean_expression;

The parameter represents the value you're testing, and the expression returns true or false.

Common Patterns

Value Range Checks:

Predicate<Integer> isPositive = n -> n > 0;
Predicate<Integer> inRange = n -> n >= 10 && n <= 100;

Null Checks:

Predicate<String> isNotNull = s -> s != null;
Predicate<String> isNullOrEmpty = s -> s == null || s.isEmpty();

Property Validation:

Predicate<String> hasMinLength = s -> s.length() >= 5;
Predicate<String> startsWithA = s -> s.startsWith("A");

Using Your Predicates

Once created, call the test method:

Predicate<Integer> isEven = n -> n % 2 == 0;

boolean result = isEven.test(4);  // true
boolean result2 = isEven.test(7); // false

Think of It Like a Question

Each predicate is a yes/no question you can ask about any value: "Is this number positive?" "Does this string start with 'A'?" Lambda syntax makes writing these questions natural and concise.

Key Takeaway: Lambda expressions let you create predicates with minimal syntax—just define what to test and the boolean condition, and Java handles the rest of the Predicate<T> implementation.