Java Stream How to - Flat map nested stream








Question

We would like to know how to flat map nested stream.

Answer

/*from  ww  w . j  a va  2 s  .co m*/
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;

public class Main {

  public static void main(String[] args) throws Exception {

    List<Foo> foos = new ArrayList<>();

    IntStream
        .range(1, 4)
        .forEach(num -> foos.add(new Foo("Foo" + num)));

    foos.forEach(f ->
        IntStream
            .range(1, 4)
            .forEach(num -> f.bars.add(new Bar("Bar" + num + " <- " + f.name))));

    foos.stream()
        .flatMap(f -> f.bars.stream())
        .forEach(b -> System.out.println(b.name));
  }

  static class Foo {
    String name;
    List<Bar> bars = new ArrayList<>();

    Foo(String name) {
      this.name = name;
    }
  }

  static class Bar {
    String name;

    Bar(String name) {
      this.name = name;
    }
  }
}

The code above generates the following result.