Issue
class MyObject {
private List<MyChildObject> children;
}
class MyChildObject {
private String key;
}
My goal is to transfor a list of MyObject
to a Map<String, MyObject>
which String
is MyChildObject.key
.
My attempt stopped at myObjectList.stream().collect(Collectors.toMap(//how to extract key here?, Function.identity()));
Thanks.
Solution
You can use flatMap
to flatten the Children to make Children's key and MyObject
pair then collect as Map using Collectors.toMap
myObjectList.stream()
.flatMap(e -> e.getChildren()
.stream()
.map(c -> new AbstractMap.SimpleEntry<>(c.getKey(), e)))
.collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));
Answered By - Eklavya
Answer Checked By - Cary Denson (JavaFixing Admin)