Map vs flatmap — Java Streams API

Hasitha Hiran
2 min readFeb 5, 2023

--

Both map and flatmap methods are intermediate operations of Java 8 Stream API. Map operation produces one output value for each input value, whereas the flatMap operation produces an arbitrary number (zero or more) values for each input value. also, Flatmap operation is the combination of Map and flat (flatten) operations. That means that you first apply a function to your elements, and then flatten it.

Difference between map and flatmap

Let’s code

Here’s a preview of the Java code that uses to explain the difference between map and flatmap.

Map

In the example above, each student has one email and multiple phone numbers.

On lines 25–27, the map operation consumes a single element from the input Stream and produces a single element in the output Stream. In this case, the output stream contains all emails of users as a list.

Flatmap

On lines 33–35, since each student has multiple phone numbers, flatmap would be ideal because one to many mapping is there. if we use a map it returns List of List because the map is not flattening the output. flatmap does both transformation and flattening.

Thanks for reading.

--

--

Hasitha Hiran

Software Engineering Graduate at Sri Lanka Institute of Information Technology(SLIIT) || Software Engineer at WILEY