Skip to content

Functional Interface

A Functional Interface is a concept in Java that enables the use of Lambda expressions.^[600-developer-java-java8-java8-lambda.md] It serves a similar role to callback functions in JavaScript, allowing actions or methods to be passed as arguments to other methods.^[600-developer-java-java8-java8-lambda.md]

Core Concept

In Java, the Function<T, R> interface is a primary example of a Functional Interface, representing a unary function that takes an argument of type T and returns a result of type R.^[600-developer-java-java8-java8-lambda.md]

The syntax for using a Functional Interface with a Lambda expression generally follows the format param -> operation.^[600-developer-java-java8-java8-lambda.md]

Usage Example

When invoking a method that accepts a Functional Interface (such as java.util.function.Function), the logic can be defined inline.^[600-developer-java-java8-java8-lambda.md]

For instance, the following operations perform different calculations on the input parameter 2:

  • Multiplication: param -> param * param
  • Addition: param -> param + param
  • Division: param -> param / param^[600-developer-java-java8-java8-lambda.md]

Common Types

Java provides several Built-in Functional Interfaces to handle different operation types:

  • Consumer\<T>: A unary function from T to void (accepts an argument, returns no result).^[600-developer-java-java8-java8-lambda.md]
  • Function\<T, R>: A unary function from T to R (accepts an argument, returns a result).^[600-developer-java-java8-java8-lambda.md]
  • Predicate\<T>: A unary function from T to boolean (accepts an argument, returns a boolean).^[600-developer-java-java8-java8-lambda.md]
  • Supplier\<T>: A nilary function to R (takes no arguments, returns a result).^[600-developer-java-java8-java8-lambda.md]
  • [[Lambda Expressions]]
  • [[Java 8]]

Sources

  • 600-developer-java-java8-java8-lambda.md