Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 310
Nick Div Avatar asked Oct 16 '16 20:10

Nick Div


People also ask

How do you stream a collection in Java?

Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. A stream is not a data structure instead it takes input from the Collections, Arrays or I/O channels.

What are the two types of collections streams offered by Java 8?

What are the two types of Streams offered by java 8? Explanation: Sequential stream and parallel stream are two types of stream provided by java.

Does Java 8 support streams?

Java 8 offers the possibility to create streams out of three primitive types: int, long and double. As Stream<T> is a generic interface, and there is no way to use primitives as a type parameter with generics, three new special interfaces were created: IntStream, LongStream, DoubleStream.


1 Answers

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

like image 52
rohitvats Avatar answered Oct 11 '22 00:10

rohitvats