Creating Function Instances with Lambdas
What you'll learn: How to implement the Function<T, R> interface using concise lambda expressions instead of verbose anonymous classes.
The Core Idea
You've seen that Function<T, R> has a single abstract method apply(T t) that transforms an input into an output. Instead of writing a full class or anonymous inner class, you can use lambda expressions to create Function instances in a single, readable line.
The lambda syntax maps naturally to Function:
- The parameter before
->represents the input (typeT) - The expression after
->represents the return value (typeR)
How It Works
Since Function is a functional interface with one method (apply), the Java compiler knows your lambda expression implements that method. You don't need to mention apply explicitly.
Basic syntax:
Function<String, Integer> stringLength = s -> s.length();
This lambda creates a Function that takes a String and returns an Integer. When you call stringLength.apply("hello"), it returns 5.
Multiple statements:
Function<String, String> formatter = s -> {
String trimmed = s.trim();
return trimmed.toUpperCase();
};
Use curly braces and explicit return for multi-line transformations.
Why This Matters
Lambdas eliminate boilerplate. Compare:
// Verbose anonymous class
Function<Integer, Integer> square = new Function<Integer, Integer>() {
public Integer apply(Integer n) {
return n * n;
}
};
// Concise lambda
Function<Integer, Integer> square = n -> n * n;
Both do the same thing, but the lambda is far more readable and maintainable.
Key Takeaway: Lambda expressions provide a clean, concise way to create Function instances by directly expressing the transformation logic without ceremonial syntax—the parameter before -> becomes the input, and the expression after becomes the result of apply().