Understanding Java 8 Predicate<T> Interface

💡 Java 8 – Predicate<T> Functional Interface Explained! The Predicate<T> is one of the most commonly used functional interfaces in Java 8, found in the package java.util.function. Predicate<T> represents a boolean-valued function of one argument. It is used to test a condition on the given input. 🔹 Method: it has boolean test method boolean test(T t) 👉 Returns true or false based on the condition. 🔹 Example: Predicate<Integer> isEven = n -> n % 2 == 0; System.out.println(isEven.test(10)); // ✅ true System.out.println(isEven.test(7)); // ❌ false 🔹 Real-world Example: List<Customer> customers = getCustomers(); Predicate<Customer> highBalance = c -> c.getBalance() > 10000; customers.stream() .filter(highBalance) .forEach(c -> System.out.println(c.getName())); 💬 Used to filter data based on conditions — powerful in Stream API! 🪄 Pro Tip: You can combine multiple predicates using: and(), or(), negate() Example: Predicate<Integer> greaterThan10 = n -> n > 10; Predicate<Integer> even = n -> n % 2 == 0; Predicate<Integer> combined = greaterThan10.and(even); System.out.println(combined.test(12)); // ✅ #Java #Java8 #FunctionalInterfaces #Predicate #JavaDeveloper #LambdaExpressions #StreamAPI #CodeWithJava #JavaProgramming #ProgrammingConcepts #FunctionalProgramming

Nice post! 👏 Predicate is also heavily used in methods like removeIf() for collections and filter() in streams, making it perfect for clean, declarative data filtering without writing explicit loops.

To view or add a comment, sign in

Explore content categories