3

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

Elad Cohen
  • 79
  • 9

1 Answers1

2

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));
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98