The apply Method: Core Transformation Logic
You'll learn how the apply method in Function<T, R> transforms one type into another.
What apply Does
The apply(T t) method is the single abstract method of the Function<T, R> interface. It takes an input of type T and returns an output of type R. This is where the actual transformation logic lives—whether you're converting a string to uppercase, extracting a property from an object, or performing calculations.
How It Works
When you create a Function using a lambda expression or method reference, you're essentially implementing the apply method. The Stream API and other functional programming tools call apply internally whenever they need to transform data.
Function<String, Integer> stringLength = s -> s.length();
Integer result = stringLength.apply("Hello"); // result is 5
In this example, the lambda s -> s.length() is the implementation of apply. When you call apply("Hello"), it executes your lambda with "Hello" as the input and returns 5.
Think of It as a Black Box
Imagine a machine where you drop in raw materials (type T) at the top, and finished products (type R) come out at the bottom. The apply method is the machinery inside that performs the conversion. You don't see the gears turning—you just provide input and receive output.
Function<Integer, String> formatter = num -> "Value: " + num;
String output = formatter.apply(42); // "Value: 42"
Key Takeaway: The apply method is the heart of Function<T, R>—it defines exactly how to transform an input of type T into an output of type R, and you implement it using lambdas or method references.