Java Predicate interface Example

🚀 Introduction to Java Predicate Functional Interface

In Java functional programming, the Predicate<T> interface (from java.util.function) is a functional interface used to test a condition. It takes an input T and returns a boolean value (true or false).

T (Input Type): The type of input value being tested.
 ✅ Return Type: boolean (true if the condition is met, otherwise false).

💡 Common Use Cases:
 ✔ Validation — Check if a number is positive, string is non-empty, etc.
 ✔ Filtering collections — Filter elements in streams based on a condition.
 ✔ Conditional logic — Apply conditions dynamically.

📌 In this article, you’ll learn:
 ✅ How to use Predicate<T> with examples.
 ✅ How to use test(), and(), or(), negate(), and isEqual().
 ✅ Real-world use cases where Predicate improves Java applications.

You can find the source code of this article on my GitHub repository.

1️⃣ Using test() Method to Check Conditions

The test(T t) method evaluates the given input and returns true or false.

✔ Checking If a Number Is Greater Than 10

import java.util.function.Predicate;

public class PredicateTestExample {
public static void main(String[] args) {
// ✅ Predicate to check if a number is greater than 10
Predicate<Integer> isGreaterThanTen = num -> num > 10;

boolean result = isGreaterThanTen.test(15);
System.out.println(result); // Output: true
}
}

📌 Why use test()?
 ✅ Encapsulates condition logic into a reusable function.
 ✅ Removes the need for separate if statements.

🚀 Use Predicate.test() to evaluate conditions in a functional way!

2️⃣ Combining Multiple Conditions Using and()

The and() method combines two predicates and returns true only if both conditions are true.

✔ Checking If a String Is Non-Empty and Has More Than 5 Characters

import java.util.function.Predicate;

public class PredicateAndExample {
public static void main(String[] args) {
// Predicate to check if a string is not empty
Predicate<String> isNotEmpty = str -> !str.isEmpty();

// Predicate to check if string length is greater than 5
Predicate<String> hasMoreThanFiveChars = str -> str.length() > 5;

// ✅ Combine predicates using and()
Predicate<String> isValid = isNotEmpty.and(hasMoreThanFiveChars);

boolean result = isValid.test("Hello World!");
System.out.println(result); // Output: true
}
}

📌 Why use and()?
 ✅ Ensures both conditions are met before returning true.
 ✅ Improves readability and modularity.

🚀 Use and() when multiple conditions must be satisfied!

3️⃣ Using or() to Check Either Condition

The or() method combines two predicates and returns true if at least one condition is true.

✔ Checking If a Number Is Less Than 5 or Greater Than 15

import java.util.function.Predicate;

public class PredicateOrExample {
public static void main(String[] args) {
// Predicate to check if a number is less than 5
Predicate<Integer> isLessThanFive = num -> num < 5;

// Predicate to check if a number is greater than 15
Predicate<Integer> isGreaterThanFifteen = num -> num > 15;

// ✅ Combine predicates using or()
Predicate<Integer> result = isLessThanFive.or(isGreaterThanFifteen);

System.out.println(result.test(3)); // Output: true
}
}

📌 Why use or()?
 ✅ Useful when either of multiple conditions can be valid.

🚀 Use or() to allow multiple valid conditions dynamically!

4️⃣ Negating a Condition Using negate()

The negate() method reverses the result of a predicate.

✔ Checking If a String Is NOT Empty

import java.util.function.Predicate;

public class PredicateNegateExample {
public static void main(String[] args) {
// Predicate to check if a string is empty
Predicate<String> isEmpty = str -> str.isEmpty();

// ✅ Negate the predicate
Predicate<String> isNotEmpty = isEmpty.negate();

boolean result = isNotEmpty.test("Hello");
System.out.println(result); // Output: true
}
}

📌 Why use negate()?
 ✅ Useful for reversing boolean conditions dynamically.

🚀 Use negate() when you need the opposite of a predicate!

5️⃣ Checking Equality Using Predicate.isEqual()

The isEqual() method returns true if the input exactly matches the given value.

✔ Checking If the Input String Equals "Java"

import java.util.function.Predicate;

public class PredicateIsEqualExample {
public static void main(String[] args) {
// ✅ Predicate to check if input equals "Java"
Predicate<String> isJava = Predicate.isEqual("Java");

boolean result = isJava.test("Java");
System.out.println(result); // Output: true
}
}

📌 Why use isEqual()?
 ✅ Avoids explicit equality checks inside lambda expressions.

🚀 Use Predicate.isEqual() to compare values efficiently!

6️⃣ Real-World Use Cases of Predicate Interface

✔ Use Case 1: Filtering a List of Numbers

Filtering even numbers from a list using Predicate with Streams.

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

public class FilterExample {
public static void main(String[] args) {
List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

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

List<Integer> evenNumbers = numbers.stream()
.filter(isEven)
.collect(Collectors.toList());

System.out.println(evenNumbers); // Output: [2, 4, 6, 8, 10]
}
}

📌 Why use Predicate in filtering?
 ✅ Encapsulates condition logic for reuse.
 ✅ Simplifies filtering logic in streams.

✔ Use Case 2: Validating User Input

Checking if a user-provided password is valid.

import java.util.function.Predicate;

public class UserValidation {
public static void main(String[] args) {
Predicate<String> isValidPassword = password -> password.length() >= 8;

String userPassword = "Secure123";
System.out.println("Is password valid? " + isValidPassword.test(userPassword));
}
}

📌 Why use Predicate in validation?
 ✅ Encapsulates validation logic into reusable functions.

🚀 Use Predicate for validating user input in applications!

🔥 Best Practices for Using Predicate Functional Interface

Best Practices for Using Predicate Functional Interface

🔑 Key Takeaways

The Predicate<T> interface helps evaluate conditions.
 ✅ Use test(), and(), or(), negate(), and isEqual() for different conditions.
 ✅ Apply Predicate in real-world use cases like filtering and validation.

By mastering the Predicate functional interface, your Java code will be more modular, readable, and reusable! 🚀

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare