Wednesday 18 March 2020

Java8: flatMap example

‘flatMap’ method returns a stream consisting of the results by replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element. Each mapped stream is closed after its contents have been placed into this stream.

Signature
<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper);

For example, let’s use flatMap to convert Stream<List<Integer>> to Stream<Integer>.

Example
List<Integer> primeNumbers = Arrays.asList(2, 3, 5, 7);
List<Integer> evenNumbers = Arrays.asList(2, 4, 6, 8);
List<Integer> oddNumbers = Arrays.asList(1, 3, 5, 7);

List<List<Integer>> allTypeOfNumbers = Arrays.asList(primeNumbers, evenNumbers, oddNumbers);

List<Integer> allNumbers = allTypeOfNumbers.stream().flatMap(list -> list.stream()).collect(Collectors.toList());

App.java
package com.sample.app;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class App {

 public static void main(String args[]) {
  List<Integer> primeNumbers = Arrays.asList(2, 3, 5, 7);
  List<Integer> evenNumbers = Arrays.asList(2, 4, 6, 8);
  List<Integer> oddNumbers = Arrays.asList(1, 3, 5, 7);

  List<List<Integer>> allTypeOfNumbers = Arrays.asList(primeNumbers, evenNumbers, oddNumbers);

  List<Integer> allNumbers = allTypeOfNumbers.stream().flatMap(list -> list.stream())
    .collect(Collectors.toList());

  allNumbers.stream().forEach(ele -> System.out.print(ele + ", "));
 }

}

Output
2, 3, 5, 7, 2, 4, 6, 8, 1, 3, 5, 7,




Previous                                                    Next                                                    Home

No comments:

Post a Comment