Swiftorial Logo
Home
Swift Lessons
AI Tools
Learn More
Career
Resources

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:

  1. Use map() when transforming elements one-to-one.
  2. Use flatMap() when each element is itself a stream or collection.
  3. 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.