如何在键位于子属性列表中时使用Collectors.toMap来收集对象?

huangapple go评论58阅读模式
英文:

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>`,其中 `String``MyChildObject.key`。

我的尝试在 `myObjectList.stream().collect(Collectors.toMap(//如何在这里提取键?, Function.identity()));` 处停止了。

谢谢
英文:
class MyObject {
  private List&lt;MyChildObject&gt; children;
}
class MyChildObject {
  private String key;
}

My goal is to transfor a list of MyObject to a Map&lt;String, MyObject&gt; which String is MyChildObject.key.

My attempt stopped at myObjectList.stream().collect(Collectors.toMap(//how to extract key here?, Function.identity()));

Thanks.

答案1

得分: 4

可以使用 flatMap 来展开 Children,将 Children 的键和 MyObject 对进行配对,然后使用 Collectors.toMap 将其收集为 Map。

myObjectList.stream()
            .flatMap(e -> e.getChildren()
                           .stream()
                           .map(c -> new AbstractMap.SimpleEntry<>(c.getKey(), e)))
            .collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));
英文:

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 -&gt; e.getChildren()
                           .stream()
                           .map(c -&gt; new AbstractMap.SimpleEntry&lt;&gt;(c.getKey(), e)))
            .collect(Collectors.toMap(e -&gt; e.getKey(), e -&gt; e.getValue()));

huangapple
  • 本文由 发表于 2020年10月9日 04:03:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/64269841.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定