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
Runnable r = new Runnable() { @Override public void run() { System.out.println("Running..."); }};
Runnable r = () -> System.out.println("Running...");
List<String> names = List.of("John", "Jane", "Jim");
names.stream() .filter(name -> name.startsWith("J")) .forEach(System.out::println);
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();
}
}