πŸ” What is a Predicate?

AΒ Predicate in Java is a functional interface that represents a boolean-valued function (i.e., it returns true or false) for a single input.

βœ… Used mainly in filtering, validations, and conditional logic, especially in Streams and Lambdas.


πŸ“¦ Predicate Interface Declaration

@FunctionalInterface
public interface Predicate<T> {
Β  Β  boolean test(T t);
}
  • It’s in the package: java.util.function.Predicate


πŸ§ͺ Basic Example

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

System.out.println(isEven.test(10)); // true
System.out.println(isEven.test(7)); Β // false


πŸ” Using Predicate with Streams

List<String> names = Arrays.asList("Aftab", "Nitin", "Ankit", "Neha");

Predicate<String> startsWithA = name -> name.startsWith("A");

names.stream()
Β  Β  Β .filter(startsWithA)
Β  Β  Β .forEach(System.out::println);
// Output: Aftab, Ankit


πŸ”— Predicate Methods

Method Description Example
test(T t) Returns true or false isEven.test(4) β†’ true
and(Predicate other) Combines two predicates with logical AND isEven.and(gtTen)
or(Predicate other) Combines with logical OR isEven.or(gtTen)
negate() Reverses the condition isEven.negate()
isEqual(Object o) Static method to check equality Predicate.isEqual("test")

🧠 Example with and():

Predicate<Integer> isEven = x -> x % 2 == 0;
Predicate<Integer> gtTen = x -> x > 10;

Predicate<Integer> evenAndGT10 = isEven.and(gtTen);

System.out.println(evenAndGT10.test(12)); // true
System.out.println(evenAndGT10.test(8)); Β // false


βœ… Summary

Feature Value
Type Functional Interface
Package java.util.function
Method boolean test(T t)
Use Cases Filters, validations, conditions
Lambda-Friendly βœ… Yes
Back to blog

Leave a comment

Please note, comments need to be approved before they are published.