A Deep Dive into the flatMap Operation of the Stream API in Java with Examples

Abdelbaki BEN ELHAJ SLIMENE
4 min readAug 10, 2023

The flatMap operation is an intermediate operation provided by the Stream API, which allows you to transform each element of a stream into zero or more elements and then flatten the resulting elements into a single stream. It's helpful to use with nested data structures, such as lists within lists and effectively "flattening" them into a more manageable format.

Photo by LekoArts on Unsplash

In this article, we will explain how this operation works internally and give some examples.

How Does 'flatMap' Operation Work?

The flatMap operation has the following signature in the Stream API:

<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper);

Here's what the components of this signature mean:

  • T: The type of elements in the original stream.
  • R: The type of elements in the resulting stream after applying the mapping function.
  • mapper: A function that takes an element of type T from the original stream and returns a stream of elements of type R.

The function is applied to each element in the original stream, and the resulting streams are then flattened into a single stream of type R.

--

--