Java 8 Functional Interfaces: Explained with Examples

📌 Java 8 Functional Interfaces — Explained with Use Cases Java provides built-in functional interfaces to support lambda expressions and functional programming. Here are the most important ones every Java developer should know: --- 1️⃣ Runnable @FunctionalInterface public interface Runnable {   void run(); } ✔ Takes: No input   ✔ Returns: Nothing  Use Case: • Multithreading tasks Example: Runnable r = () -> System.out.println("Task running"); --- 2️⃣ Callable @FunctionalInterface public interface Callable<V> {   V call() throws Exception; } ✔ Takes: No input   ✔ Returns: Result  Use Case: • Tasks that return values (ExecutorService) Example: Callable<Integer> c = () -> 10; --- 3️⃣ Comparator @FunctionalInterface public interface Comparator<T> {   int compare(T o1, T o2); } ✔ Takes: Two inputs   ✔ Returns: int  Use Case: • Sorting collections Example: list.sort((a, b) -> a - b); --- 4️⃣ Function<T, R> ✔ Takes: One input   ✔ Returns: One output  Use Case: • Transforming data Example: Function<String, Integer> f = s -> s.length(); --- 5️⃣ Predicate<T> ✔ Takes: One input   ✔ Returns: boolean  Use Case: • Filtering conditions Example: Predicate<Integer> p = x -> x > 10; --- 6️⃣ Consumer<T> ✔ Takes: One input   ✔ Returns: Nothing  Use Case: • Performing actions (printing, logging) Example: Consumer<String> c = s -> System.out.println(s); --- 7️⃣ Supplier<T> ✔ Takes: No input   ✔ Returns: Value  Use Case: • Lazy value generation Example: Supplier<Double> s = () -> Math.random(); --- 🧠 Quick Summary Runnable → No input, no output   Callable → No input, returns output   Function → Input → Output   Predicate → Input → boolean   Consumer → Input → action   Supplier → No input → output  --- 💡 Key Takeaway These interfaces form the backbone of Java 8 features like Streams and Lambdas. Mastering them helps write clean, functional, and expressive code. #Java #Java8 #FunctionalInterfaces #Lambda #BackendDevelopment

To view or add a comment, sign in

Explore content categories