Functional Interface

 A functional interface is an interface with exactly one abstract method (but can have multiple default or static methods). We need to annotate with @FunctionalInterface (optional but recommended for clarity).

Built-in Functional Interfaces:-

Java 8 provides several predefined functional interfaces in java.util.function:

  • Predicate<T> → (filtering) Tests a condition (boolean test(T t))
  • Function<T, R> →  (transformation) Takes input T, returns R (R apply(T t))
  • Consumer<T> → (action on each element) Accepts input, no return (void accept(T t))
  • Supplier<T> → (lazy generation) No input, returns T (T get())
  • Comparator<T> → sorting

Why Use Functional Interfaces?

1. Enable Lambda Expressions
They are the backbone of using lambdas, which help simplify your code.

Without functional interface:
 
  
Runnable r = new Runnable() {
    @Override
    public void run() {
        System.out.println("Running...");
    }
};
With functional interface (lambda):

  Runnable r = () -> System.out.println("Running...");
 

2. Cleaner and More Readable Code

You reduce boilerplate code, especially for one-method logic like filtering, mapping, or sorting.


List<String> names = List.of("John", "Jane", "Jim");
names.stream()
     .filter(name -> name.startsWith("J"))
     .forEach(System.out::println);
Here, Predicate<T> and Consumer<T> are built-in functional interfaces.

3. Promotes Functional Programming Style

Functional interfaces let you treat functions as first-class citizens, enabling a more declarative programming style.

Example:- Sample example without and with a functional interface and lambda interface.

@FunctionalInterface

public interface Bike {

public void pulsar();

}

public class BikeImpl implements Bike{

@Override

public void pulsar() {

System.out.println("This is pulsar method implementation");

}

}

public class FunInterfaceTest {

public static void main(String[] args) {

// Without a functional interface and lambda

BikeImpl bike = new BikeImpl();

bike.pulsar();

}

}

With a Functional interface and lambda expression, No need for BikeImpl.java class just need the Bike.java functional interface and the main method to call it.

public class FunInterfaceTest {

 public static void main(String[] args) {

//Using the functional interface and lambda

Bike bikeFn = () -> System.out.println("This is functional interface call using lambda expression");

bikeFn.pulsar();

}

}

Post a Comment (0)
Previous Post Next Post