Q56: What is the difference between map() and flatMap() in Java Streams?

  • map(): $1 o 1$ transformation. Applies a mapping function to each element, returning Stream<T>.
  • flatMap(): $1 o N$ transformation. Applies a function that returns a Stream for each element, flattening nested streams (Stream<Stream<T>>) into a single unified Stream<T>.
flatMap Example
List<List<String>> nestedList = List.of(
    List.of("A", "B"),
    List.of("C", "D")
);

List<String> flatList = nestedList.stream()
    .flatMap(Collection::stream) // Flattens nested streams into one stream
    .toList(); // [A, B, C, D]
💡 flatMap extracts elements from inner collections and merges them into a single linear stream.
Key Takeaways
  • map() transforms values 1-to-1 (List<String> -> List<Integer>). flatMap() flattens nested structures (List<List<String>> -> List<String>).
Knowledge Check

Which operation should be used to transform a List<Order> (where each Order contains a List<Item>) into a single flat List<Item>?