Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Streams and List of List of List [duplicate]

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.

like image 713
Clomez Avatar asked Feb 05 '19 11:02

Clomez


Video Answer


1 Answers

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>
like image 160
Eran Avatar answered Nov 06 '22 23:11

Eran