Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
Functional Interface in Java is defined using the @FunctionalInterface annotation in Java, which ensures the interface meets the required condition. There are different types of functional interfaces in Java, such as Runnable, Callable, Predicate, and more, commonly used in stream and lambda operations..
In this article, we will discuss the functional interface in Java. We will discuss how we can implement it. We will also discuss its types. So, a functional interface only has one abstract method. Before diving into the topic, let us understand what an interface is in Java.
What are the Functional Interfaces in Java?
Functional interfaces in Java are interfaces that have exactly one abstract method, making them ideal for use with lambda expressions and method references. These interfaces provide the foundation for functional programming in Java, introduced in Java 8. They are marked with the @FunctionalInterface annotation in Java, which signals the compiler to ensure the interface has only one abstract method.
There are several types of functional interfaces in Java, including:
Runnable – represents a task with no input and no result.
Callable – returns a result and may throw an exception.
Predicate<T> – takes one input and returns a boolean.
Function<T, R> – takes one input and returns a result.
Consumer<T> – takes one input and returns nothing.
Supplier<T> – returns a result with no input.
These interfaces play a key role in lambda expressions, stream APIs, and concise, clean code design in Java.
In Java 8, we got this type of interface along with an amazing feature called lambda expression. The @FunctionalInterface annotation indicates that an interface is a functional interface.
Now you might be thinking, how this functional interface looks like. So, let us understand this interface with the help of an example.
Example of Functional Interface in Java
Here is an example of the functional interface in Java:
This code defines a functional interface called GreetingForNinjas that has a single abstract method called greetNinja(). The method takes only a single parameter of type String and returns no value.
The @FunctionalInterface annotation is an optional annotation for the functional interface. This annotation tells the compiler that this interface is a functional interface. If you try to add one more abstract method it will throw an error because of the functional interface property of having only one abstract method.
Now we can use this functional interface to greet a Ninja.
public class NinjaGreetings {
public static void main(String[] args) {
// Creating a lambda expression
GreetingForNinjas greetNinja = (nameOfNinja) -> System.out.println("Hello, " + nameOfNinja + "!");
// Using the lambda expression as a value
greetNinja.greetNinja("Narayan Mishra");
}
}
You can also try this code with Online Java Compiler
In this example, a lambda expression is used to implement the GreetingForNinja interface. The lambda expression takes a single parameter, nameOfNinja, and uses it to print a greeting message. Then the greetNinja() method of the GreetingForNinja interface is called with the nameOfNinja.
Output
Hello, Narayan Mishra!
Types of Functional Interfaces in Java
There are different types of functional interfaces present in the java.util.function package. Let us understand a few of them:
1. Consumer
A Consumer is a functional interface that represents an operation that accepts an input, performs some action on it, but does not return a result in the Java language's java.util.function package. It accepts an argument and executes the operation. It is often used for side-effect activities like printing, logging, or object modification. Accept is the only abstract method that the Consumer interface defines. It helps to represent an operation that accepts a single input argument and returns no result.
Example
import java.util.function.Consumer;
public class Example {
public static void main(String[] args) {
// Define a Consumer to print a string
Consumer<String> printString = str -> System.out.println(str);
// Use the Consumer to print a message
printString.accept("Consumer Functional Interface");
}
}
You can also try this code with Online Java Compiler
A Predicate is a functional interface that represents a boolean-valued function of an input in the Java java.util.function package. It is frequently used to put a condition to the test and see if it holds true or not. One abstract method named test is defined in the Predicate interface. It helps to represent a predicate or boolean-valued function of one argument. It is used to filter out the values from the collection in Java.
Example
import java.util.function.Predicate;
public class Example {
public static void main(String[] args) {
// Define a Predicate to check if a number is even
Predicate<Integer> isEven = num -> num % 2 == 0;
// Test the Predicate
boolean result = isEven.test(10);
System.out.println("Is 10 even? \n" + result); // Output: Is 10 even? true
}
}
You can also try this code with Online Java Compiler
A function that takes an input and produces an output is represented by a functional interface called a function in Java's java.util.function package. Data transformation or mapping from one type to another is frequently utilised. The apply abstract method, which accepts an argument and produces a result, is the only one that the Function interface defines.
Example
import java.util.function.Function;
public class Example {
public static void main(String[] args) {
// Define a Function to double a number
Function<Integer, Integer> doubleNumber = num -> num * 2;
// Use the Function to double a number
int result = doubleNumber.apply(10);
System.out.println("Double of 10 is: " + result);
}
}
You can also try this code with Online Java Compiler
A Supplier is a functional interface that represents a supplier of results in Java's java.util.function package; when called, it does not require any input and instead returns a result. It is frequently utilised when you need to create or compute values inefficiently.
Example
import java.util.function.Supplier;
public class Example {
public static void main(String[] args) {
// Define a Supplier to generate a random number
Supplier<Double> randomNumberSupplier = () -> Math.random();
// Use the Supplier to generate a random number
double randomVal = randomNumberSupplier.get();
System.out.println("Random Number: " + randomVal);
}
}
You can also try this code with Online Java Compiler
The @FunctionalInterface annotation in Java is used to indicate that an interface is intended to be a functional interface—an interface with exactly one abstract method. This annotation was introduced in Java 8 to support lambda expressions and functional programming features.
By using @FunctionalInterface, the compiler checks that the interface contains only one abstract method. If more than one abstract method is declared, the compiler will generate an error, ensuring the integrity of the functional interface.
You can still have default or static methods in a functional interface, as long as there is only one abstract method.
This annotation enhances code readability and compiler-level validation, making it easier to implement lambda expressions and method references in modern Java applications.
Built-in Java Functional Interfaces
There are four built-in functional interfaces in Java:
Runnable: The runnable interface in Java helps us to define a method called run(). This method doesn't takes any arguments and returns no value. It is used to represent a task that can be executed asynchronously.
Callable: The callable interface in Java helps us to define a method called call(). This method returns a value of a specific type and can throw an exception. It is used to represent a task that can be executed asynchronously and that returns a result.
Comparable: The comparable interface in Java helps us to define a method called compareTo(). This method takes an object of the same type as the implementing class. It returns an integer value indicating the ordering of the two objects. It is used to represent objects that have a natural ordering, such as numbers or strings.
ActionListener: The ActionListener interface in Java helps us to define an abstract method actionPerformed(ActionEvent e). This interface handles events triggered by actions such as button clicks, menu selections, and other user interactions.
Table of Functional Interfaces in Java
Functional Interface
Description
Abstract Method
Runnable
Represents a task that runs with no input and returns no result.
void run()
Callable<V>
Represents a task that returns a result and may throw an exception.
V call()
Supplier<T>
Supplies a result without taking any input.
T get()
Consumer<T>
Performs an action on a single input with no return value.
void accept(T t)
Function<T, R>
Takes one argument and returns a result.
R apply(T t)
Predicate<T>
Evaluates a condition on a given input and returns a boolean result.
boolean test(T t)
BiFunction<T, U, R>
Takes two arguments and returns a result.
R apply(T t, U u)
BiConsumer<T, U>
Performs an action on two inputs and returns nothing.
void accept(T t, U u)
BiPredicate<T, U>
Evaluates a condition on two inputs and returns a boolean.
boolean test(T t, U u)
UnaryOperator<T>
A Function that takes one argument and returns the same type.
T apply(T t)
BinaryOperator<T>
A BiFunction where both operands and result are of the same type.
T apply(T t1, T t2)
Frequently Asked Questions
What is functional interface in Java?
A functional interface is a type of interface. It has only one abstract method. This interface is used to show a single functionality. We can use functional interfaces where methods are treated as values, such as lambda expressions.
What is the use of @FunctionalInterface annotation?
It ensures the interface has only one abstract method, allowing it to be used with lambda expressions and enforcing compiler-level validation.
What are the benefits of a functional interface?
It enables cleaner, more readable code using lambda expressions, supports functional programming, and simplifies passing behavior as parameters in Java methods.
What do you understand by a lambda expression?
A lambda expression is a feature of Java 8. It is the easiest way to declare a function along with its parameters. It is a short way in Java to express a function. This can work as a value, and later on, we can use this value in our code.
Is it possible to have more than one abstract method for a functional interface?
No, this is not possible in the case of a functional interface in Java. This interface can only have one abstract method. If it has more than one abstract method, then this will not be anymore a functional interface.
What are the ways to create a functional interface?
There are several ways to create a functional interface. We can create a functional interface by defining an interface with only one abstract method. We can also use the @FunctionalInterface annotation. This annotation helps us to indicate an interface as a functional interface.
Conclusion
In this article, we have discussed the functional interface in Java. We have also discussed examples by using this interface. With the advent of lambda expressions in Java 8, functional interfaces have become increasingly important in Java development. They give programmers an easy method to treat functions as first-class citizens, allowing them to create clearer and more expressive code.