Java Functional Interfaces (original) (raw)

Last Updated : 15 Apr, 2025

A functional interface in Java is an interface that contains only one abstract method. Functional interfaces can have multiple default or static methods, but only one abstract method. **Runnable, **ActionListener,** and **Comparatorare common examples of **Java **functional interfaces. From **Java 8 onwards, **lambda expressions and **method references can be used to represent the instance of a functional interface.

**Example: Using a Functional Interface with Lambda Expression

Java `

public class Geeks {

public static void main(String[] args) {
  
    // Using lambda expression 
    // to implement Runnable
    new Thread(() -> System.out.println("New thread created")).start();
}

}

`

**Explanation: In the above example, we can see the use of a lambda expression to implement the **Runnable functional interface and create a new thread.

**Functional Interface is additionally recognized as **Single Abstract Method Interfaces. In short, they are also known as **SAM interfaces. Functional interfaces in Java are a new feature that provides users with the approach of fundamental programming.

**Note: A functional interface can also extend another functional interface.

The ****@FunctionalInterface** annotation can be used to indicate that an interface is intended to be a functional interface. If an interface has more than one abstract method, it cannot be a functional interface.

****@FunctionalInterface** Annotation

@FunctionalInterface annotation is used to ensure that the functional interface cannot have more than one abstract method. In case more than one abstract methods are present, the compiler flags an "**Unexpected @FunctionalInterface annotation" message. However, it is not mandatory to use this annotation.

**Note: @FunctionalInterface annotation is optional but it is a good practice to use. It helps catching the error in early stage by making sure that the interface has only one abstract method.

**Example: Defining a Functional Interface with ****@FunctionalInterface Annotation**

Java `

// Define a functional interface @FunctionalInterface

interface Square { int calculate(int x); }

class Geeks { public static void main(String args[]) { int a = 5;

    // lambda expression to 
    // define the calculate method
    Square s = (int x) -> x * x;

    // parameter passed and return type must be
    // same as defined in the prototype
    int ans = s.calculate(a);
    System.out.println(ans);
}

}

`

**Explanation: In the above example, the **Square interface is annotated as a **functional interface. Then the lambda expression defines the calculate method to compute the square of the number.

Java Functional Interfaces Before Java 8

Before Java 8, we had to create anonymous inner class objects or implement these interfaces. Below is an example of how the **Runnable interface was implemented prior to the introduction of lambda expressions.

**Example:

Java `

// Java program to demonstrate functional interface // before Java 8 class Geeks { public static void main(String args[]) {

    // create anonymous inner class object
    new Thread(new Runnable() {
        @Override public void run()
        {
            System.out.println("New thread created");
        }
    }).start();
}

}

`

Built-In Java Functional Interfaces

Since Java SE 1.8 onwards, there are many interfaces that are converted into functional interfaces. All these interfaces are annotated with ****@FunctionalInterface**. These interfaces are as follows:

Types of Functional Interfaces in Java

**Java SE 8 included four main kinds of functional interfaces which can be applied in multiple situations as mentioned below:

  1. **Consumer
  2. **Predicate
  3. **Function
  4. **Supplier

1. Consumer

The consumer interface of the functional interface is the one that accepts only one argument or a gentrified argument. The consumer interface has no return value. It returns nothing. There are also functional variants of the Consumer — DoubleConsumer, IntConsumer, and LongConsumer. These variants accept primitive values as arguments.

Other than these variants, there is also one more variant of the Consumer interface known as Bi-Consumer.

**Syntax / Prototype of Consumer Functional Interface:

Consumer consumer = (value) -> System.out.println(value);

This implementation of the Java Consumer functional interface prints the value passed as a parameter to the print statement. This implementation uses the Lambda function of Java.

2. Predicate

The Predicate interface represents a boolean-valued function of one argument. It is commonly used for filtering operations in streams.

Just like the Consumer functional interface, Predicate functional interface also has some extensions. These are IntPredicate, DoublePredicate, and LongPredicate. These types of predicate functional interfaces accept only primitive data types or values as arguments.

**Syntax:

public interface Predicate {

boolean test(T t);

}

The Java predicate functional interface can also be implemented using **Lambda expressions.

Predicate predicate = (value) -> value != null;

3. Function

A function is a type of functional interface in Java that receives only a single argument and returns a value after the required processing. Many different versions of the function interfaces are instrumental and are commonly used in primitive types like double, int, long.

**Syntax:

Function<Integer, Integer> function = (value) -> value * value;

4. Supplier

The Supplier functional interface is also a type of functional interface that does not take any input or argument and yet returns a single output.

The different extensions of the Supplier functional interface hold many other suppliers functions like BooleanSupplier, DoubleSupplier, LongSupplier, and IntSupplier. The return type of all these further specializations is their corresponding primitives only.

**Syntax:

Supplier supplier = () -> "Hello, World!";

Functional Interfaces Table

Functional Interfaces Description Method
Runnable It represents a task that can be executed by a thread. void run()
Comparable It compares two objects for ordering. int compareTo(T o)
ActionListener It handles an action event in event-driven programming. void actionPerformed(ActionEvent e)
Callable It represents a task that can return a result or throw an exception. V call() throws Exception
Consumer It accepts a single input argument and returns no result. void accept(T t)
Predicate It accepts a single argument and returns a boolean result. boolean test(T t)
Function It accepts a single argument and returns a result. R apply(T t)
Supplier It does not take any arguments but provides a result. T get()
BiConsumer It accepts two arguments and returns no result. void accept(T t, U u)
BiPredicate It accepts two arguments and returns a boolean result. boolean test(T t, U u)
BiFunction It accepts two arguments and returns a result. R apply(T t, U u)
UnaryOperator This is a special case of Function, where input and output types are the same. T apply(T t)
BinaryOperator This is a special case of BiFunction, where input and output types are the same. T apply(T t1, T t2)

**Example: Using Predicate Interface to Filter Strings

Java `

// Demonstrate Predicate Interface import java.util.*; import java.util.function.Predicate;

class Geeks { public static void main(String args[]) {

    // create a list of strings
    List<String> n = Arrays.asList(
        "Geek", "GeeksQuiz", "g1", "QA", "Geek2");

    // declare the predicate type as string and use
    // lambda expression to create object
    Predicate<String> p = (s) -> s.startsWith("G");

    // Iterate through the list
    for (String st : n) {
      
        // call the test method
        if (p.test(st))
            System.out.println(st);
    }
}

}

`

Output

Geek GeeksQuiz Geek2

**Important Points: