Java Functional Interface
What is a Functional Interface?
A Functional Interface is simply an interface that has only one abstract method.
interface Greeting {
void sayHello();
}It has only one method. Java calls this a Functional Interface.
You can even write
@FunctionalInterface
interface Greeting {
void sayHello();
}The annotation (@FunctionalInterface) is optional, but it tells Java:
“This interface must always have exactly one abstract method.”
If you accidentally add another abstract method
@FunctionalInterface
interface Greeting {
void sayHello();
void bye();
}Java gives an error.
Why were Functional Interfaces created?
Before Java 8, if you wanted to pass some behavior (code) to another method, you had to create a class.
class GreetingImpl implements Greeting {
public void sayHello() {
System.out.println("Hello");
}
}Then
Greeting g = new GreetingImpl();
g.sayHello();Lots of code.
Java 8 introduced Lambda Expressions, but lambdas need something to fit into.
That “something” is a Functional Interface.
Think of it like this
Lambda
↓
must fit into
↓
Functional InterfaceWithout Functional Interfaces, Lambda Expressions wouldn’t exist.
Real-life analogy
Imagine a TV remote.
Power ButtonThe remote has one button When you press it, something happens. You don’t care how it happens. Same idea.
A Functional Interface is like
Button
↓
One actionWhenever someone presses it, Java executes whatever code you supplied.
Type Functional Interfaces
1. Consumer
Get Bishal Saha’s stories in your inbox
Join Medium for free to get updates from this writer.
Input
Yes
Output
Nothing
Consumer<String> c = name -> System.out.println(name);Think
Take
↓
Use
↓
Done2. Supplier
Input
Nothing
Output
Something
Supplier<Integer> s = () -> 10;Think
Give me something3. Function
Input
Yes
Output
Yes
Function<String,Integer> f = name -> name.length();Think
Input
↓
Process
↓
Return result4. Predicate
Input
Yes
Output
true/false
Predicate<Integer> p = x -> x > 10;Think
Question
↓
Answer
↓
True or False





