top of page
Search

Java 8 Stream.flatMap

  • schick09
  • Aug 2, 2024
  • 2 min read

Updated: Aug 3, 2024

Java 8’s Stream.flatMap() is used in cases where you have a ‘Stream of Streams’ and you want to return a single Stream.  It’s all about merging multiple collections into a single collection (array, list, etc).  The flatMap() operation takes the objects from all of the collections in the original Stream and combines them into a single stream (which can then be converted into a collection).

 

flatMap() returns a new Stream made up of the results of applying a mapping function to each element of a stream and then flattening the stream returned into a single stream.

 

The map() operation on the other hand uses a function to transform each element of a stream into another object, returning a new stream made up of the new object (in the same order as the original Stream).


In this case, each input element is transformed to a single new output element.  For example, if there are 10 elements in the input Stream, there will be 10 transformed elements in the output Stream.

 

The flatMap() operation is used in cases where each element of the input Stream is being transformed into several elements (e.g., each new transformed element is a Stream itself, etc). 


So in this case, an input element is converted into a collection of multiple output elements which are then ‘flattened’ down into a single collection of output elements.

 

Consider a situation where you have a List<List<Car>> where Car is a custom class describing car make, model, body style, etc.  You may have this data structure because you are retrieving lists of cars from several different databases.  But at the end of the day, you just want a List<Car>.  If you apply flatMap() to this List<List<Car>> you will end up with List<Car>.

 

List<Car> flattenedList = carListofLists.stream()
  .flatMap(list -> list.stream())
 .toList();

Here's a link to our GitHub location to access an example of using Stream.flatMap: https://github.com/daveschickconsulting/java_8_examples/tree/main/src/funwithjava8flatmap





 
 
 

Comments


Dave Schick Consulting

©2023 by Dave Schick Consulting. Proudly created with Wix.com

bottom of page