-1
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.

LunaticJape
  • 1,446
  • 4
  • 21
  • 39

1 Answers1

4

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()));
Eklavya
  • 17,618
  • 4
  • 28
  • 57