flatMap() example



Example:

import java.util.Arrays;
import java.util.List;

public class FlatMapFlight {
    public static void main(String[] args) {
        System.out.println("main() [Start]");
        List<String> words = Arrays.asList("Hello","Good","Morning");
       
        words
        .stream()
        .map(word->word.split(""))
        .flatMap(Arrays::stream)
        .forEach(System.out::println);
       
        System.out.println("main() [End]");
    }
}


Ouput:
main() [Start]
H
e
l
l
o
G
o
o
d
M
o
r
n
i
n
g
main() [End]


Explanation:

 .map(word->word.split("")) :

  • filter takes the lamda expression as an argument. 
  • It takes a lamda expression having functional interface having abstract method which take one argument and return another type object in result. 
  • It returns the Stream of result type parameters
  • Here it returns each word in a separate stream of String  containing each character
    .flatMap(Arrays::stream):
  • This method works on the stream returned from the previous method
  • It returns the Stream merging all the words streams into a single stream
  • If you will not use flatMap here then it will give you three streams objects for the give three words each contains each character in a string
  • So, using flatMap will give you a single stream contains all words all character in a single stream.
     .forEach(System.out::println):
  • This method works on the stream returned from the flatpMap method
  • This is a terminal operation method because it doesnt return the stream.
  • All the previous streams maintained as pipeline and processed when this method get called
  • This method takes a consumer functional interface lamda expression or method reference as argument and it consumes the data of previous streams. Here it consumes and display each element.