Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert a list objects with list to map in Java 8 by stream [duplicate]

I have the following classes:

class A {
   String id;
   List<B> b;
}

class B {
   String id;
}

And I have a list of a's that I would like to convert to a map with the following logic:

List<A> aList;

Map<String, String> map; 

for (A a:aList)
{
   for (B b:aList.b)
   {
      map.put(b.id, a.id)
   }
}  

What is the best way to do it in one line of stream method?

Thanks Elad

like image 272
Elad Cohen Avatar asked Jan 17 '26 06:01

Elad Cohen


1 Answers

You can stream the each list of B class from A class object, and then collect the id combinations into Map.Entry objects

Map<String,String> map = aList.stream()
                              .flatMap(al->al.getB()
                                             .stream()
                                             .map(bl-new AbstractMap.SimpleEntry<String, String>(bl.getId(), al.getId())))
                              .collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue));
like image 157
Deadpool Avatar answered Jan 19 '26 20:01

Deadpool



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!