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.
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 Streams offered by java 8? Explanation: Sequential stream and parallel stream are two types of stream provided by java.
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.
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).
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