Explain the function interface in Java 8

In Java 8, the function interface is a central concept introduced to support functional programming and enable the creation of functional methods. A functional interface is defined as an interface that contains exactly one abstract method. These interfaces can be used as the assignment target for a lambda expression or method reference.

Java 8 provides several built-in functional interfaces in the java.util.function package, such as:

  • Function: Represents a function that accepts one argument and produces a result.
  • Consumer: Represents an operation that accepts a single input argument and returns no result.
  • Supplier: Represents a supplier of results, it does not take any input but returns a value.
  • Predicate: Represents a boolean-valued function of one argument.

Here's an example of a functional interface:

@FunctionalInterface public interface MyFunctionalInterface { void execute(String message); } public class Main { public static void main(String[] args) { MyFunctionalInterface myFunc = (message) -> System.out.println(message); myFunc.execute("Hello, Functional Interface!"); } }

Java 8 Functional Interface Lambda Expression Functional Programming java.util.function