-2

I have a class. I want to get list of objects that will contain all this parameters flat. For now I'm doing it with foreach. Is there a way to do it with flatMap?

public class A{
  String parA;
  List<B> parB;

  public static class B{
    String parC;
    String parD;
    List<C> parE;
  }

  public static class C{
    String parF;
    String parG;
    String parH;
    String parJ;
  }
} 

I want to have list of objects :

public class Out{
  String parA;
  String parC;
  String parD;
  String parF;
  String parG;
  String parH;
  String parJ;
}
Matthias
  • 4,481
  • 12
  • 45
  • 84
janneob
  • 959
  • 2
  • 11
  • 25

1 Answers1

2

Assuming you have a given A a = ... the more concise and clean approach would be two nested loops like:

List<Out> list = new ArrayList<>();
for (B b : a.parB) {
  for (C c : b.parE) {
    list.add(new Out(a.parA, b.parC, b.parD, c.parF, c.parG, c.parH, c.parJ));
  }
}

Since you've asked for a Stream solution here you go:

List<Out> list = Stream.of(a).flatMap(aa -> 
  aa.parB.stream().flatMap(bb -> 
    bb.parE.stream().map(cc -> 
      new Out(aa.parA, bb.parC, bb.parD, cc.parF, cc.parG, cc.parH, cc.parJ))
  )
).collect(Collectors.toList());
Flown
  • 11,480
  • 3
  • 45
  • 62