Function<T,R>
- Java course
- Advanced
- Lesson 13/82
- 5 min
Learn transformation functions with Function<T,R>.
The Function<T,R> interface
Function<T, R> represents a function that takes a T value and returns an R value. Its single abstract method is apply. This interface is the standard way to write transforming code concisely.
Example: Function<String, Integer> len = String::length;. Then len.apply("Alex") returns 4. You can also write the function as a lambda: s -> s.length(). Function is also often passed to map in streams.
compose and andThen
To apply two functions in sequence you use compose and andThen. Both return a new Function; the difference is the application order.
Example: f.andThen(g) applies f first, then g. f.compose(g) applies g first, then f. This is similar to function composition in mathematics; it is the clean way to pipe data through one stage into the next.
Practice Find string length with Function
Define a Function<String, Integer> that uses the String::length method reference. Then print the result of apply("Hello") with System.out.println.
Starter code
import java.util.function.Function;
// Define a length Function using String::length
// Get the length of "Hello" with apply
// Print the resultSample solution
import java.util.function.Function;
public class FunctionExample {
public static void main(String[] args) {
Function<String, Integer> len = String::length;
System.out.println(len.apply("Hello"));
}
}Expected output
5
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the single abstract method of Function<T,R>?
- apply Correct answer
- get
- test
- accept
Explanation: apply is Function's call method.
2 Complete the Function call
Function<String, Integer> len = String::length;
int n = len.____("Ayşe");
Function<String, Integer> len = String::length;
int n = len.apply("Ayşe");
Explanation: apply is Function's call method.
3 Match the Function concepts
| Term | Meaning |
|---|---|
Function<T,R> |
Takes T returns R |
apply |
Call method |
andThen |
Calls afterwards |
compose |
Calls before |