Sobes.tech
Middle

What do you know about functional interfaces in Java 8 and above?

sobes.tech AI

Answer from AI

A functional interface is an interface that contains only one abstract method. They are used for implementing lambda expressions and method references. They can have default and static methods.

Examples of built-in functional interfaces in the java.util.function package:

  • Predicate<T>: Accepts one argument of type T and returns a boolean value.
    // public boolean test(T t);
    
  • Consumer<T>: Accepts one argument of type T and returns nothing. Performs an action on the argument.
    // public void accept(T t);
    
  • Supplier<T>: Takes no arguments and returns a value of type T.
    // public T get();
    
  • Function<T, R>: Accepts an argument of type T and returns a value of type R.
    // public R apply(T t);
    

The @FunctionalInterface annotation is optional but recommended for compiler checks and clarity.

@FunctionalInterface
interface MyFunction {
    String process(String input);
    
    default void doNothing() {
        // Default method
    }
}