Java 8 Stream flatMap

In this article, we will discuss Java 8 Stream flatMap.

Stream flatMap()

Stream flatMap is a combination of two operations .. a map operation and a flatten operation.

To understand this, consider an example of multiple lists of elements like {a,b}, {c,d,e},.. etc.

Now, if we want to get all the elements in sequence, we can’t use a map since we have a non-flat structure here.

For this, we can use flatMap() to flatten it to a structure like {a,b,c,d,e,.. } . Then we can use any other map or filter operations on it.

The below diagram demonstrates this :

java 8 stream flatmap
 

Java 8 Streams flatMap method examples

Example 1 : Converting Stream of List of Strings to uppercase

Stream<List<String>> strStream = Stream.of(Arrays.asList("a", "b"),
    Arrays.asList("c", "d"));
strStream.flatMap(str -> str.stream()).
      map(String::toUpperCase).
      forEach(System.out::println);

Output:

A
B
C
D
 

Example 2 : Getting all even numbers from Stream of multiple list of numbers

In this example, we have a Stream of multiple lists of numbers and we are looking to get numbers from it in sequence.

Stream<List<Integer>> numberStream = Stream.of(
    Arrays.asList(1, 2, 3, 4), Arrays.asList(5, 6, 7, 8));

numberStream.flatMap(n -> n.stream())
      .filter(n -> n % 2 == 0)
      .forEach(System.out::println);

Output:

2
4
6
8

 

Example 3 : Printing list of all files in current directory and all of its sub-directories

Stream<File> fileStream = Stream.of(new File(".").listFiles());
fileStream.flatMap(file -> file.listFiles() == null ? Stream.of(file) : Stream.of(file.listFiles()))
    .forEach(System.out::println);

Here, the lambda expression provided to flatMap gets the files in any sub-directories or returns the current file name.

The flatMap method returns a flattened map of a collection of all the children of the current directory’s sub-directories
 

Difference between map and flatMap methods in Java 8

The map operation takes a Function, which is called for each value in the input stream and produces one result value, which is sent to the output stream.

flatMap function works the same way as the map function, but instead of producing a single element, it produces a Stream of elements.

flatMap lets us replace a value with a Stream and concatenates all the streams together.

 

© 2016 – 2018, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags