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

0

1 Answer 1

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));
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Deadpool! Actually you can use Map.entry instead of new AbstractMap.SimpleEntry<String, String>

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.