I'd like to retrieve the distinct list of Longs given this nested structure:
Class A
public List<B> getBs()
Class B
public List<Long> getIds()
List<A> list = ...
// how do I now get all of longs as a distinct list
I realise I can do 2 for loops but given Java8's new abilities which I'm only just getting used to I'm sure there is a better way.
To clarify, I require List<long> (not List<A>)
Thanks
Something like the code below should work - you go down the nested structure with map, then you "flatMap" the list of ids into one concatenated stream of Longs on which you can apply the distinct intermediate operation.
List<A> list = ...;
List<Long> uniqueIds = list.stream() //Stream<A>
.map(A::getBs) //Stream<List<B>>
.flatMap(List::stream) //Stream<B>
.map(B::getIds) //Stream<List<Long>>
.flatMap(List::stream) //Stream<Long>
.distinct()
.collect(toList());
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