Function<T, R> is a functional interface in java.util.function representing a transformation that takes one argument of type T and produces a result of type R, defined by its single abstract method apply(T t).
Key Points: • Function is generic over both its input and output types, making it flexible for any one-argument transformation. • It's the type expected by Stream.map(), which applies the function to every stream element to produce a transformed stream. • Function provides default methods andThen() and compose() to chain multiple functions together into a single pipeline. • Primitive specializations like IntFunction, ToIntFunction, and IntUnaryOperator avoid boxing overhead for primitive types. • BiFunction<T, U, R> extends the same concept to two input arguments.
Example: Function<String, Integer> parseLength = String::length; can be passed to stream.map(parseLength) to turn a stream of strings into a stream of their lengths.
Code Example:
Function<Integer, Integer> square = x -> x * x;
Function<Integer, Integer> addOne = x -> x + 1;
Function<Integer, Integer> combined = square.andThen(addOne);
System.out.println(combined.apply(3)); // 10 -> (3*3)+1Interview Tip: A concise interview answer is:
"Function<T, R> represents a transformation from one type to another through its apply() method, and it's the interface Stream.map() expects. Its andThen() and compose() default methods let me chain multiple functions into a pipeline, which is handy for building reusable transformation steps."