Java 8 Streams flatmap examples

In this tutorial we will be looking into the Java 8 streams flatmap method. The flatmap() method is a little confusing to understand at first so I will do my best.

A visual way to understand a flatmap is the following, suppose you have a structure like [[100,200,300], [400,500,600], [700] ] applying flatmap to this structure will result in [100,200,300,400,500,600,700]. As you can see the structure of the result has flattened the structure into one array.

Simple Java 8 Streams flatMap example:

The following example takes a List of List<String> and it will flatten it to a List<String>.

Running the above code produces the following output

Java 8 Streams flatMap example with Objects:

The second example make use of a pojo object called UserCoins

The aim of the following code is to collect all the user coins. It makes use of map() to return a new Stream of Stream<List<String>> and then we use flatmap to convert the stream to a Stream<String> which gives us the user coins.

Running the above code produces the following output

I hope you found the post useful and it provided an insight on how to use the flatmap() method.

Similar posts:

  1. Java 8 Stream filter example
  2. Java 8 Stream map example
  3. Java 8 forEach example
  4. How to convert Java object to JSON


  1. Java 8 Stream API Documentation


Leave a Reply