Nick Div Nick Div - 1 year ago 104
Java Question

How do I run nested collect on java 8 stream

I have a list of objects A, A has a property called Address which has a street name -- streetName

From the list of objects A I want to getList of all the street names. One level collection seems quite doable from streams but how do I get nested String using one line of code.

So for getting list of addresses from object A I can do this:;

My ultimate aim is to get list of street names, so I am not able to figure out a second level collection using lambdas.

I couldnt find the precise example I was looking for. Could someone please help me with this.

Answer Source

You can simply chain another map operation to get the street names:

.map(a -> a.getStreetName())  // or a::getStreetName

The first map transforms your objects into Address objects, the next map takes those Address objects and transforms them into street names, which are then collected by the collector.

The stream operations form a pipeline, so you can have as many operations as you need before the terminal operations (in this case, the collect operation).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download