Java Stream How to - Map int array to Object








Question

We would like to know how to map int array to Object.

Answer

/* w w  w . j a  v  a2s  .  c o  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 {
    IntStream
        .range(1, 4)
        .mapToObj(num -> new Foo("Foo" + num))
        .peek(
            f -> IntStream.range(1, 4)
                .mapToObj(num -> new Bar("Bar" + num + " <- " + f.name))
                .forEach(f.bars::add)).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.