flatMap in Java 8 - Part 2

In Java 8 the most important library changes are made in Collection API and there is also a new addition named Stream. Streams allow us to write collections-processing code at a higher level of abstraction. Stream can hold different types of data, following are some examples:

Stream<String []>      : A Stream of Array of Strings
Stream<Set<String>>    : A Stream of Set of Strings or a Stream of identical Strings
Stream<List<String>>   : A Stream of List of Strings
Stream<List<Object>>   : A Stream of List of Objects.


Now the Stream interface contains a series of functions which corresponds to a common operation that you might perform on a Collection like filter, sum, distinct etc. But these functions and Collectors cannot be applied upon above Stream of data. We need a flat Stream of data for applying these above methods. We can use flatMap() method to convert a hierarchical Stream to a flat Stream.  flatMap() can do the following conversion :

Stream<String[]>     -> flatMap   ->    Stream<String>
Stream<String[]>     -> flatMap   ->    Stream<String>
Stream<Set<String>>  -> flatMap   ->    Stream<String>
Stream<List<String>> -> flatMap   ->    Stream<String>
Stream<List<Object>> -> flatMap   ->    Stream<Object>

Following is an example of the transformation done by flatMap():

How flatMap() works :

{ {1,2}, {3,4}, {5,6} }  -> flatMap -> {1,2,3,4,5,6}

{ {'a','b'}, {'c','d'}, {'e','f'} } -> flatMap -> {'a','b','c','d','e','f'}

 Following is an example where we can flattens a 2D array of Strings as a Stream of String by using the flatMap() method.

/**
 * Example of converting a 2D array of String to a Stream of Strings
 */
String[][] programmingLanguage = new String[][] {
 {
  "Java",
  "C"
 }, {
  "C++",
  "PHP"
 }, {
  "R",
  "Go"
 }
};
Stream < String[] > tempStream = Arrays.stream(programmingLanguage);
Stream < String > stringStream = tempStream.flatMap(x -> Arrays.stream(x));

// Now as the stream is flattened, we can perform filter on it
// Find all programming languages, which starts with the letter C
Stream < String > filteredStream = stringStream.filter(x -> x.startsWith("C"));
filteredStream.forEach(System.out::println);

 Following is an example where we can flattens multiple Lists of Strings using the flatMap() method.

/**
 * Example of Concatenating multiple Collections to a Stream
 */
List < String > objectOrientedPL = Arrays.asList("Java", "Python", "Ruby", "C++");
List < String > proceduralPL = Arrays.asList("C", "Lisp");

List < String > allPL = Stream.of(objectOrientedPL, proceduralPL)
 .flatMap(strings -> strings.stream())
 .collect(Collectors.toList());

// Print all the Concatenated programming languages
allPL.forEach(System.out::println);

The full code used in this example is given below:

package com.tuturself;

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

public class StreamExample {

 public static void main(String[] args) {

  /**
   * Example of converting a 2D array of String to a Stream of Strings
   */
  String[][] programmingLanguage = new String[][] {
   {
    "Java",
    "C"
   }, {
    "C++",
    "PHP"
   }, {
    "R",
    "Go"
   }
  };
  Stream < String[] > tempStream = Arrays.stream(programmingLanguage);

  Stream < String > stringStream = tempStream.flatMap(x -> Arrays.stream(x));

  // Now as the stream is flattened, we can perform filter on it
  // Find all programming languages, which starts with the letter C
  Stream < String > filteredStream = stringStream.filter(x -> x.startsWith("C"));
  filteredStream.forEach(System.out::println);

  System.out.println("---- SEPERATOR ------");

  /**
   * Example of Concatenating multiple Collections to a Stream
   */
  List < String > objectOrientedPL = Arrays.asList("Java", "Python", "Ruby", "C++");
  List < String > proceduralPL = Arrays.asList("C", "Lisp");

  List < String > allPL = Stream.of(objectOrientedPL, proceduralPL)
   .flatMap(strings -> strings.stream())
   .collect(Collectors.toList());

  // Print all the Concatenated programming languages
  allPL.forEach(System.out::println);
 }
}

 

CORE JAVA JAVA-8 STREAM