6

For some reason I can't wrap my head around how to turn this deeply nested list into a new list using streams.

   every A in List<A> contains -> 
   List<B> where every B contains -> 
   List<C> where every C contains -> List<String>

I have tried many different iterations like:

  List<String> newlist =  listA.getB()
                   .stream()
                   .filter(b -> b.getC()
                   .stream()
                   .filter(c -> c.getPeople)
                   .collect(Collectors.toList())

I'm full of confusion... I could easily do this with for loops but I've heard that streams are simple and easy and I would like to start using them more.

Lino
  • 19,604
  • 6
  • 47
  • 65
Clomez
  • 1,410
  • 3
  • 21
  • 41

1 Answers1

14

You should use flatMap:

List<String> newList =
    listA.stream() // Stream<A>
         .flatMap(a->a.getB().stream()) // Stream<B>
         .flatMap(b->b.getC().stream()) // Stream<C>
         .flatMap(c->c.gtPeople().stream()) // Stream<String>
         .collect(Collectors.toList()); // List<String>
Eran
  • 387,369
  • 54
  • 702
  • 768