Wednesday 18 March 2020

flatMap: Convert Stream to Stream

‘flatMap’ method returns a stream consisting of the results of 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);

Example
Integer[] primeNumbers = { 2, 3, 5, 7 };
Integer[] evenNumbers = { 2, 4, 6, 8 };
Integer[] oddNumbers = { 1, 3, 5, 7 };

Integer[][] allTypeOfNumbers = { primeNumbers, evenNumbers, oddNumbers };

Stream<Integer[]> allNumbers = Arrays.stream(allTypeOfNumbers);

Stream<Integer> intStream = allNumbers.flatMap(arr -> Arrays.stream(arr));

App.java
package com.sample.app;

import java.util.Arrays;
import java.util.stream.Stream;

public class App {

 public static void main(String args[]) {
  Integer[] primeNumbers = { 2, 3, 5, 7 };
  Integer[] evenNumbers = { 2, 4, 6, 8 };
  Integer[] oddNumbers = { 1, 3, 5, 7 };

  Integer[][] allTypeOfNumbers = { primeNumbers, evenNumbers, oddNumbers };

  Stream<Integer[]> allNumbers = Arrays.stream(allTypeOfNumbers);

  Stream<Integer> intStream = allNumbers.flatMap(arr -> Arrays.stream(arr));

  intStream.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