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
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));
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