Functional Interfaces

Functional Interfaces A Functional Interface is an interface with exactly one abstract method. It forms the foundation for lambda expressions in Java. Declaration @FunctionalInterface interface MyFunctionalInterface { void execute(); } The @FunctionalInterface annotation is optional but recommended. Having more than one abstract method will result in a compilation error if the annotation is present. Example with Lambda public class Main { public static void main(String[] args) { MyFunctionalInterface f = () -> System.out.println("Executed!"); f.execute(); } } Built-in Functional Interfaces (in java.util.function) Predicate<T> – returns boolean Function<T, R> – returns a value Consumer<T> – performs an action Supplier<T> – provides a value Predicate<String> isLong = s -> s.length() > 5; System.out.println(isLong.test("Hello")); // false Benefits Enables cleaner, more modular code Essential for lambda expressions Supports functional programming 🔗 Related Notes Lambdas Generic Methods

May 8, 2025 · 1 min · Rohan

Lambdas

Lambdas Lambdas in Java are anonymous functions that can be treated as objects and passed around. Introduced in Java 8, they enable functional programming features such as concise function representations and behavior passing. Syntax (parameters) -> expression (parameters) -> { statements } Example interface Greeting { void sayHello(); } public class Main { public static void main(String[] args) { Greeting g = () -> System.out.println("Hello, Lambda!"); g.sayHello(); } } With Parameters interface MathOperation { int operation(int a, int b); } public class Main { public static void main(String[] args) { MathOperation add = (a, b) -> a + b; System.out.println(add.operation(5, 3)); // Output: 8 } } Use with Collections List<String> list = Arrays.asList("A", "B", "C"); list.forEach(item -> System.out.println(item)); Benefits Shorter code Improved readability Enables functional-style programming 🔗 Related Notes Functional Interfaces Generic Methods

May 8, 2025 · 1 min · Rohan