Java Predicate Function Consumer Differences Explained

🚀 Java Backend Interview Series – Question #72 Q72. What is the difference between Predicate, Function, and Consumer in Java? In Java 8, functional interfaces made it easier to write clean and expressive code using lambdas. Among the most commonly used ones are: 👉 Predicate 👉 Function 👉 Consumer Understanding the difference between them is very important for interviews and real-world backend development. Let’s break it down 👇 🔹 1️⃣ Predicate 👉 Used for conditions (boolean checks) ✔ Takes one input ✔ Returns boolean Example: Predicate<Integer> isEven = n -> n % 2 == 0; System.out.println(isEven.test(10)); // true 📌 Use case: ✔ Filtering data ✔ Validations 🔹 2️⃣ Function<T, R> 👉 Used for transformation (input → output) ✔ Takes one input ✔ Returns one result Example: Function<String, Integer> getLength = str -> str.length(); System.out.println(getLength.apply("Java")); // 4 📌 Use case: ✔ Data transformation ✔ Mapping values 🔹 3️⃣ Consumer 👉 Used for performing actions ✔ Takes one input ✔ Returns nothing (void) Example: Consumer<String> print = str -> System.out.println(str); print.accept("Hello Java"); 📌 Use case: ✔ Logging ✔ Printing ✔ Updating values 🔹 Key Differences InterfaceInputOutputUse CasePredicate1booleanCondition checkFunction11 valueTransformationConsumer1voidAction🔹 Real-World Backend Example List<String> users = List.of("Admin", "User", "Guest"); users.stream() .filter(u -> u.startsWith("A")) // Predicate .map(String::toUpperCase) // Function .forEach(System.out::println); // Consumer 📌 This is how they work together in real applications. 🎯 Interview Tip A common tricky question: 👉 “Can we combine multiple Predicates?” Answer: ✔ Yes, using: and() or() negate() 💬 Follow-up Interview Question What is the difference between Function and UnaryOperator in Java? #Java #Java8 #FunctionalProgramming #Predicate #Function #Consumer #JavaDeveloper #BackendDevelopment #CodingInterview #TechInterview #SoftwareEngineering #SpringBoot #Microservices #Programming #CleanCode

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories