Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get concatenation of nested List<Long> with java collector

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

like image 765
Manish Patel Avatar asked Mar 14 '23 23:03

Manish Patel


1 Answers

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());
like image 192
assylias Avatar answered Apr 07 '23 07:04

assylias