Java Functional Interfaces
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 Comparator are 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 1: Using a Functional Interface with Lambda Expression
public class Geeks {
public static void main(String[] args) {
// Using lambda expression
// to implement Runnable
new Thread(() -> System.out.println("New thread created")).start();
}
}
Output
New thread created
Explanation: In the above example, we can see the use of 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 the new feature that provides users with the approach of fundamental programming.
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.
Example: Defining a Functional Interface with @FunctionalInterface Annotation
// 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);
}
}
Output
25
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 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();
}
}
Output
New thread created
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:
- Runnable: This interface only contains the run() method.
- Comparable: This interface only contains the compareTo() method.
- ActionListener: This interface only contains the actionPerformed() method.
- Callable: This interface only contains the call() method.
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:
- Consumer
- Predicate
- Function
- 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<Integer> 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<T> {
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;
- Bi-Function: The Bi-Function is substantially related to a Function. Besides, it takes two arguments, whereas Function accepts one argument.
- Unary Operator and Binary Operator: There are also two other functional interfaces which are named Unary Operator and Binary Operator. They both extend the Function and Bi-Function, respectively. In simple words, Unary Operator extends Function, and Binary Operator extends Bi-Function.
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<String> supplier = () -> “”;
Functional Interfaces Table
Functional Interfaces | Description | Method |
---|---|---|
It represents a task that can be executed by a thread. | void run() | |
It compares two objects for ordering. | int compareTo(T o) | |
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 |
It accepts a single input argument and returns no result. | void accept(T t) | |
It accepts a single argument and returns a boolean result. | boolean test(T t) | |
It accepts a single argument and returns a result. | R apply(T t) | |
It does not take any arguments but provides a result. | T get() | |
It accepts two arguments and returns no result. | void accept(T t, U u) | |
It accepts two arguments and returns a boolean result. | boolean test(T t, U u) | |
It accepts two arguments and returns a result. | R apply(T t, U u) | |
This is a special case of Function, where input and output types are the same. | T apply(T t) | |
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
// 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:
- In functional interfaces, there is only one abstract method supported. If the annotation of a functional interface, i.e., @FunctionalInterface is not implemented or written with a function interface, more than one abstract method can be declared inside it. However, in this situation with more than one functions, that interface will not be called a functional interface. It is called a non-functional interface.
- There is no such need for the @FunctionalInterface annotation as it is voluntary only. This is written because it helps in checking the compiler level. Besides this, it is optional.
- An infinite number of methods (whether static or default) can be added to the functional interface. In simple words, there is no limit to a functional interface containing static and default methods.
- Overriding methods from the parent class do not violate the rules of a functional interface in Java.
- The java.util.function package contains many built-in functional interfaces in Java 8.