Functional Interface : Function
What is a Functional Interface?
A functional interface is an interface that has only one abstract method.
Java provides some built-in functional interfaces. One of them is:
Function<T, R>It means:
Take one input and return one output.
For example:
Function<Integer, Integer> square = x -> x * x;Here:
Integer→ input typeInteger→ return typex -> x * x→ the function
So:
Input → Function → Output5 → x * x → 25Functional Interface in JWT Example
This code has:
private <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {
final Claims claims = extractAllClaims(token);
return claimsResolver.apply(claims);
}The important part is:
Function<Claims, T> claimsResolverThis means:
“Give me a function that takes
Claimsas input and returns some typeT."
For example, when we call:
extractClaim(token, Claims::getSubject);Claims::getSubject is the function.
Get Bishal Saha’s stories in your inbox
Join Medium for free to get updates from this writer.
It can be understood as:
claims -> claims.getSubject()So the flow is:
JWT Token
↓
extractAllClaims()
↓
Claims object
↓
claimsResolver
↓
getSubject()
↓
UsernameExample 1: Getting Username
We have:
public String extractUsername(String token) {
return extractClaim(token, Claims::getSubject);
}Here:
Claims::getSubjectmeans:
claims -> claims.getSubject()So the Function receives:
Claimsand returns:
StringTherefore:
Function<Claims, String>Why did we create extractClaim()?
Without a functional interface, wecould write separate logic for every claim.
But with:
Function<Claims, T>we can make one reusable method:
extractClaim(token, Claims::getSubject);The method doesn’t need to know which claim you want.
You simply give it a function that tells it what to extract.
Easy way to remember
Think of Function as a worker:
Claims
↓
┌─────────────────┐
│ Function │
│ "What to get?" │
└─────────────────┘
↓
ResultFor username:
Claims → getSubject() → StringIn one line
Function<Claims, T> is a functional interface that allows your extractClaim() method to accept different functions for extracting different values from JWT claims.








