Java - Streams Flatten Operation

Introduction

Streams supports one-to-many mapping through the flatMap operation.

Suppose that you have a stream of three numbers: 1, 2, and 3.

You want to produce a stream that contains the numbers and the square of the numbers.

You want the output stream to contain 1, 1, 2, 4, 3, and 9.

Demo

import java.util.stream.Stream;

public class Main {
  public static void main(String[] args) {
    Stream.of(1, 2, 3)/*  w  ww .  j  a v a 2s  .c  o  m*/
    .flatMap(n -> Stream.of(n, n * n))
    .forEach(System.out::println);
  }
}

Result

The following code counts the number of the Es in the strings.

The code maps the strings to IntStream.

chars() method of the String class returns an IntStream, not a Stream<Character>.

The output of the map() method is Stream<IntStream>.

The flatMap() method maps the Stream<IntStream> to Stream<Stream<Character>> and finally, flattens it to produce a Stream<Character>.

The output of the flatMap() method is Stream<Character>.

The filter() method filters out any characters that are not an E or e.

count() method returns the number of elements in the stream.

The main logic is to convert the Stream<String> to a Stream<Character>.

Demo

import java.util.stream.Stream;

public class Main {
  public static void main(String[] args) {
    long count = Stream.of("Java", "Jeff", "Python")//
        .map(name -> name.chars())//
        .flatMap(intStream -> intStream.mapToObj(n -> (char)n))//
        .filter(ch -> ch == 'e' || ch == 'E')//
        .count();//
    System.out.println(count);/*from w w  w . j  a  v a  2 s.  co  m*/
  }
}

Result

You can achieve the same using the following code as well:

Demo

import java.util.stream.IntStream;
import java.util.stream.Stream;

public class Main {
  public static void main(String[] args) {
    long count = Stream.of("Java", "Jeff", "Python")
        .flatMap(name -> IntStream.range(0, name.length())
                                  .mapToObj(name::charAt))
        .filter(ch -> ch == 'e' || ch == 'E')
        .count();/*  w w w  .  j  a  va  2s . c  o m*/
    System.out.println(count);
  }
}

Result