Common Use Cases: Mapping and Transformation
What You'll Learn
You'll discover how to apply Function<T, R> in collections, streams, and map operations to transform data efficiently.
Why Functions Excel at Transformation
Think of a Function as a conversion machine: you feed in raw material (type T) and get back a finished product (type R). In Java, these "machines" shine when you need to transform collections of data—converting user objects to names, prices to formatted strings, or raw inputs to processed outputs.
Applying Functions in Collections
The most common place you'll use Function is with the Stream.map() operation:
List<String> names = List.of("alice", "bob", "charlie");
// Transform to uppercase using Function
List<String> upperNames = names.stream()
.map(String::toUpperCase) // Function<String, String>
.toList();
// Result: ["ALICE", "BOB", "CHARLIE"]
Transforming Complex Objects
Functions really prove their worth when extracting or converting properties:
List<Person> people = /* ... */;
List<String> emails = people.stream()
.map(Person::getEmail) // Function<Person, String>
.toList();
Using Functions with Map Operations
You can transform map values using computeIfAbsent, replaceAll, and similar methods:
Map<String, Integer> scores = new HashMap<>();
scores.put("Alice", 85);
// Transform value using Function
scores.replaceAll((name, score) -> score + 10); // BiFunction here
Chaining Transformations
Combine functions with andThen for multi-step transformations in streams:
Function<String, String> trim = String::trim;
Function<String, String> upper = String::toUpperCase;
List<String> cleaned = inputs.stream()
.map(trim.andThen(upper))
.toList();
Key Takeaway: Function is your go-to tool for transforming data in streams and collections—use it with map() to convert elements, extract properties, or apply any type-changing operation to each item in a collection.