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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With