Java Streams: map() vs flatMap()

Java Streams: map() vs flatMap()

In Java Streams, both map() and flatMap() are used to transform data — but they behave differently based on the output structure. Let's break it down with real examples.

map() – One-to-One Transformation

Transforms each element into another value (e.g., String to Integer):

List<String> names = List.of("Alice", "Bob");

List<Integer> lengths = names.stream()
    .map(String::length)
    .collect(Collectors.toList());

System.out.println(lengths); // Output: [5, 3]

flatMap() – One-to-Many Flattening

Each element is mapped to a Stream, and all streams are then flattened into a single stream:

List<String> sentences = List.of("Hello world", "Java Streams");

List<String> words = sentences.stream()
    .flatMap(s -> Arrays.stream(s.split(" ")))
    .collect(Collectors.toList());

System.out.println(words); // Output: [Hello, world, Java, Streams]

🔁 Key Differences

Feature map() flatMap()
Transformation One-to-One One-to-Many
Output Type Stream<T> Stream<U> (flattened)
Use Case Transform each item Flatten nested structures

📦 Nested List Example

List<List<String>> listOfLists = List.of(
    List.of("A", "B"),
    List.of("C", "D")
);

// Using map()
Stream<List<String>> mapped = listOfLists.stream().map(list -> list);
System.out.println(mapped.count()); // Output: 2

// Using flatMap()
Stream<String> flatMapped = listOfLists.stream().flatMap(List::stream);
System.out.println(flatMapped.count()); // Output: 4

🎯 Conclusion

  • Use map() for simple transformations.
  • Use flatMap() when each element produces a stream or collection, and you want a single flattened result.

Mastering these two functions makes your Java Stream operations far more powerful and expressive!

Comments

Popular posts from this blog

Spring Boot with AI

Voice & Chatbots – AI-Assisted Conversational Apps

Java 17 Features