Sobes.tech
Junior — Middle

Can you explain how the flatMap method works in the Stream API and when it should be used?

sobes.tech AI

Answer from AI

The flatMap method in the Stream API is used to transform each element of a stream into another stream, and then flatten (concatenate) all the resulting streams into one.

Unlike map, which transforms an element into a single object, flatMap allows you to obtain multiple elements (or none at all) from a single element.

Example usage:

List<String> phrases = List.of("Hello world", "Java streams");
List<String> words = phrases.stream()
    .flatMap(phrase -> Arrays.stream(phrase.split(" ")))
    .collect(Collectors.toList());
// words will contain: ["Hello", "world", "Java", "streams"]

When to use flatMap:

  • When you need to obtain multiple elements from a single element.
  • For working with nested data structures (e.g., list of lists).
  • To simplify chains of transformations to get a flat stream of elements.