Java 8 FAQ: Top Questions
15. What is the purpose of the map() method in Java 8 Streams?
The map()
method is an intermediate operation in the Java 8 Stream API that applies a transformation function to each element of the stream. It is used to convert elements from one form to another.
πΊοΈ Step-by-Step Instructions:
- Use
map()
to apply a function to every element in the stream. - Each input element is transformed individually and returns a new stream.
- Common transformations include converting data types, applying business rules, or formatting output.
π₯ Example Input:
List names = Arrays.asList("alice", "bob", "claire");
List uppercased = names.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
π Expected Output:
[ALICE, BOB, CLAIRE]
β Java 8 Solution:
import java.util.*;
import java.util.stream.*;
public class StreamMapExample {
public static void main(String[] args) {
List names = Arrays.asList("alice", "bob", "claire");
List uppercased = names.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
System.out.println(uppercased);
}
}
π Detailed Explanation:
- map(): Applies a transformation function to each element.
- Returns: A new stream with the transformed elements.
- Common usage: Formatting strings, converting types, applying computations.
π οΈ Use Cases:
- Converting numeric values (e.g., from
int
todouble
). - Formatting names or data before display.
- Applying business logic transformations in a clean way.