Nick Div Nick Div - 1 month ago 17
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:

listOfObjectsA.stream().map(a::getAddress).collect(Collectors.toList());


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

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

listOfObjectsA
.stream()
.map(a::getAddress)
.map(a -> a.getStreetName())  // or a::getStreetName
.collect(Collectors.toList());

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).