Functional Interfaces & Method References in Java
A functional interface is any interface with exactly one abstract method — that single-method constraint is precisely what makes it possible for a lambda expression to implement it, since the lambda's body has an unambiguous single method to become. Java's standard library ships a set of common, ready-made functional interfaces in java.util.function so most everyday needs don't require defining a custom one: Function<T,R> takes a T and returns an R, Predicate<T> takes a T and returns a boolean, Consumer<T> takes a T and returns nothing, and Supplier<T> takes nothing and returns a T.
A method reference, written as ClassName::methodName or object::methodName, is an even shorter alternative to a lambda whenever the lambda would do nothing but call one existing method directly. String::toUpperCase used as a Function<String,String> is exactly equivalent to writing s -> s.toUpperCase(), just without repeating a parameter name that isn't adding any information.
Exactly one abstract method
That single-method rule is what qualifies an interface as functional and lets a lambda implement it.
Common built-in functional interfaces
Function<T,R>, Predicate<T>, Consumer<T>, and Supplier<T> cover most everyday needs without a custom interface.
The @FunctionalInterface annotation
Optional, but documents intent and makes the compiler flag it as an error if a second abstract method is ever added by mistake.
Method references as shorthand
ClassName::methodName or object::methodName replaces a lambda that would just call one existing method with nothing else added.
Four kinds of method references
A static method, an instance method on a particular object, an instance method on an arbitrary object of a type, and a constructor can each be referenced this way.
import java.util.function.Function; public class FunctionalDemo { public static void main(String[] args) { Function<String, String> shout = String::toUpperCase; System.out.println(shout.apply("hello")); }}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Java yourself — building beats watching.