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.
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
public class Geeks {
public static void main(String[] args) {
// Using lambda expression to implement Runnable
new Thread(() -> System.out.println("New thread created")).start();
}
}
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:
- Above program demonstrates use of lambda expression with the Runnable functional interface.
- Runnable has one abstract method run(), so it qualifies as a functional interface.
- Lambda ()-> System.out.println("New thread created") defines the run() method.
- new Thread().start() starts a new thread that executes the lambda body
Note: A functional interface can also extend another 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
@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);
}
}
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:
- Square is a functional interface with a single method calculate(int x).
- A lambda expression (int x) -> x * x is used to implement the calculate method.
- Lambda takes x as input and returns x * x.
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
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();
}
}
class Geeks {
public static void main(String args[]) {
// create anonymous inner class object
new Thread(new Runnable() {
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 as Unary Operator and Binary Operator. They both extend the Function and Bi-Function respectively, where both the input type and the output type are same.
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 = () -> "Hello, World!";
Example: Using Predicate Interface to Filter Strings
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);
}
}
}
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
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) |