Wednesday 18 March 2020

Java: map vs flatMap

a. map function takes a stream as input and transform it to other stream. For example, I can use map function to convert a stream of integers to stream of squares.
‘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>.
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[]) {

  // map demo
  List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

  List<Integer> squares = numbers.stream().map(number -> number * number).collect(Collectors.toList());

  squares.stream().forEach(n -> System.out.print(n + " "));

  // flatMap demo
  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());

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

 }

}


Output
1 4 9 16 25
2 3 5 7 2 4 6 8 1 3 5 7


b. map() is used to transform the data, whereas flatMap can be used for both transformation and flatening.


You may like

No comments:

Post a Comment