The Function<T, R> Interface and Its Purpose
What you'll learn: You'll discover how Function<T, R> transforms input values into output values using a single-method functional interface.
What is Function<T, R>?
Function<T, R> is a functional interface in the java.util.function package that represents a transformation operation. It accepts one argument of type T and produces a result of type R. Think of it like a mathematical function: you put something in, and you get something different out.
The single abstract method is apply(T t), which performs the transformation.
The Core Purpose
While Predicate answers yes/no questions, Function performs conversions or mappings. It's perfect for scenarios where you need to:
- Convert one data type to another
- Extract a property from an object
- Apply a calculation or transformation
- Map values in a stream
Analogy: Think of Function as a vending machine. You insert a coin (input type T), and the machine dispenses a snack (output type R). The coin and snack are different things, but the machine knows how to transform your input into the output.
Basic Examples
// String length calculator
Function<String, Integer> lengthFunction = str -> str.length();
Integer length = lengthFunction.apply("Hello"); // Returns 5
// Convert to uppercase
Function<String, String> toUpper = String::toUpperCase;
String result = toUpper.apply("java"); // Returns "JAVA"
// Parse string to integer
Function<String, Integer> parser = Integer::parseInt;
Integer number = parser.apply("42"); // Returns 42
In Practice with Streams
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
List<Integer> lengths = names.stream()
.map(name -> name.length()) // Function<String, Integer>
.collect(Collectors.toList()); // [5, 3, 7]
Key Takeaway: Function<T, R> is the go-to functional interface for transforming values from one type to another, making it essential for mapping operations throughout Java's functional programming features.