Function
TL;DR
Function<T, R>is a built-in functional interface in thejava.util.functionpackage.- It takes one argument of type T, performs an operation, and returns a result of type R.
- It is primarily used for mapping or transforming data from one form to another.
- Its abstract method is
R apply(T t).
Concept
A Function is the workhorse of functional transformations. Any time you have an object and you need to convert it into a different object (or extract a specific field from it), you use a Function.
For example, converting a String to an Integer (parsing), or taking a User object and returning just their String email address. This is heavily used in the Stream API’s map() operation.
Examples
import java.util.function.Function;
public class FunctionExample {
public static void main(String[] args) {
// Function<InputType, ReturnType>
// Takes a String, returns an Integer (its length)
Function<String, Integer> stringLength = str -> str.length();
System.out.println(stringLength.apply("Hello World")); // 11
// --- Chaining Functions ---
Function<Integer, Integer> multiplyByTwo = n -> n * 2;
Function<Integer, Integer> addTen = n -> n + 10;
// andThen() executes the first function, then passes its result to the second.
// 5 * 2 = 10 -> 10 + 10 = 20
Function<Integer, Integer> chainedFunction = multiplyByTwo.andThen(addTen);
System.out.println(chainedFunction.apply(5)); // 20
}
}
Interview Questions
Q: What is the difference between Function.andThen() and Function.compose()?
A: Both are used to chain two functions together, but they evaluate in reverse order.
f1.andThen(f2): Executesf1first, then passes the result tof2.f1.compose(f2): Executesf2first, then passes the result tof1.
Q: What is a BiFunction?
A: BiFunction<T, U, R> is a variation of Function that takes two arguments (T and U) and returns a single result (R). Its abstract method is R apply(T t, U u). It’s commonly used in operations like Map.computeIfPresent(), where you are given both a key and a value, and must return a new value.