Java 8 FAQ: Top Questions
9. What is the difference between map() and flatMap() in Java 8 Streams?
The methods map()
and flatMap()
are used to transform elements in a Stream. The key difference is that map()
produces one output per input, while flatMap()
flattens multiple nested streams into a single one.
πΊοΈ Step-by-Step Instructions:
- Use
map()
when transforming elements one-to-one. - Use
flatMap()
when each element is itself a stream or collection. flatMap()
flattens nested structures (e.g., lists of lists).
π₯ Example Input:
List words = Arrays.asList("hello", "world");
// Using map()
List> mapped = words.stream()
.map(word -> Arrays.stream(word.split("")))
.collect(Collectors.toList());
// Using flatMap()
List flatMapped = words.stream()
.flatMap(word -> Arrays.stream(word.split("")))
.collect(Collectors.toList());
π Expected Output of flatMapped:
[h, e, l, l, o, w, o, r, l, d]
β Java 8 Solution:
import java.util.*;
import java.util.stream.*;
public class FlatMapExample {
public static void main(String[] args) {
List words = Arrays.asList("hello", "world");
List result = words.stream()
.flatMap(word -> Arrays.stream(word.split("")))
.collect(Collectors.toList());
System.out.println(result);
}
}
π Detailed Explanation:
- map(): Transforms each element into another form, retaining stream structure.
- flatMap(): Flattens resulting sub-streams into one unified stream.
- Common in use cases like list of lists, or converting lines to words in text processing.
π οΈ Use Cases:
- Flattening nested data (e.g.,
List<List<String>>
). - Processing lines into words in text analysis.
- API calls that return nested structures.