如果键在子 属性 列表中,如何使用 Collectors.toMap 收集对象?

How to collect object using Collectors.toMap if the key is inside a list of child property?

class MyObject {
  private List<MyChildObject> children;
}
class MyChildObject {
  private String key;
}

我的目标是将 MyObject 的列表转换为 Map<String, MyObject>,其中 StringMyChildObject.key

我的尝试停止在 myObjectList.stream().collect(Collectors.toMap(//how to extract key here?, Function.identity()));

谢谢。

您可以使用 flatMap 展平子对象以制作子对象的密钥和 MyObject 对,然后使用 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()));