Wednesday, November 23, 2022

A Sip of Java: Stream.flatMap()

 Let's say you have a map where you store a list of values for each key, something like:


And now you want a single list with all values in the Map. Then you need to use flatMap:

Map.values() returns a collection of the values for each key in the map, since each value is a list of Strings, it will return a collection of list of strings.

But you want a single list with all strings right?

Ok, then use Stream.flatMap() method to get a stream for each list in the collection of values and then merge all lists into a single list.

Simply put, convert a Stream of Stream of values into a single list of values.

No comments: