Skip to content

Functional Interface

A functional interface is an interface with exactly one abstract method. That single method becomes a landing pad for a lambda expression, so you can pass behavior like a value âš¡


🧠 Key Idea

One abstract method → one lambda → clean, concise code

You can still have default and static methods; only the count of abstract methods must be one.


🔹 Basic Example

@FunctionalInterface
interface Greeting {
    void sayHello(String name);
}

Using Lambda

Greeting g = (name) -> System.out.println("Hello " + name);
g.

sayHello("Swapnil");

🔹 Built-in Functional Interfaces

Java ships many ready-to-use ones:

  • Predicate → boolean test(T t)
  • Function → R apply(T t)
  • Consumer → void accept(T t)
  • Supplier → T get()

🚀 Practical Examples

1) Predicate – filtering

import java.util.*;
import java.util.function.Predicate;

List<Integer> nums = Arrays.asList(1, 2, 3, 4, 5);

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

nums.stream()
    .filter(isEven)
    .forEach(System.out::println); // 2, 4

2) Function – transform data

import java.util.function.Function;

Function<String, Integer> lengthFn = s -> s.length();

System.out.println(lengthFn.apply("Java")); // 4

3) Consumer – perform action

import java.util.function.Consumer;

Consumer<String> printer = s -> System.out.println(s);

printer.

accept("Hello");

4) Supplier – generate value

import java.util.function.Supplier;

Supplier<Double> random = () -> Math.random();

System.out.

println(random.get());

5) Custom Functional Interface

@FunctionalInterface
interface Calculator {
    int compute(int a, int b);
}

Calculator add = (a, b) -> a + b;
Calculator multiply = (a, b) -> a * b;

System.out.

println(add.compute(2, 3));      // 5
        System.out.

println(multiply.compute(2, 3)); // 6

6) Sorting with Comparator

import java.util.*;

List<String> list = Arrays.asList("Banana", "Apple", "Mango");

list.

sort((a, b) ->a.

compareTo(b));
        System.out.

println(list);

🎯 Interview Answer

A functional interface is an interface with exactly one abstract method and is used as the basis for lambda expressions. It allows passing behavior as a parameter and is widely used in Java 8 features like Stream API, filtering with Predicate, transformation with Function, and actions with Consumer.


🧠 Mental Model

A functional interface is like a single-slot socket 🔌 Plug in any lambda, and it powers that behavior instantly.