【问题标题】:Java stream collect as a map using streamed element as key and collected list as value?Java流收集作为地图使用流元素作为键和收集的列表作为值?
【发布时间】:2022-01-19 21:19:01
【问题描述】:

所以我看到了一些与此类似的问题,但无法将他们的答案应用于我的代码,我想知道如何做到这一点。所以基本上我有以下代码(简化):

public Map<String, List<String>> myFunction(String myApp) {
  List<String> myIds = myService.getIds(myApp);

  return myIds.stream()
      .map(id -> {
          final List<String> myObjects = myService.getListForId(id);
          return new MyWrapper(id, myObjects);
      }).collect(Collectors.toMap(a -> a.ID, a -> a.OBJECTS);
}

class MyWrapper {
    public final String ID;
    public final List<String> OBJECTS;

    public MyWrapper(String id, List<String> objects) {
        ID = id;
        OBJECTS = objects;
    }
}

我不知道如何在 Collectors 函数中访问 id,因为列表与 id 没有可获取的关系,因此我创建了一个包装类来存储这两个值。关于在没有包装器的情况下做到这一点的任何想法?谢谢

【问题讨论】:

    标签: java java-stream collectors


    【解决方案1】:
    • 通过myService.getIds流式传输ID
    • 然后简单地将这些ids 映射到服务返回的列表(使用方法引用)。
    Map<String, List<String>> map = myService.getIds(myApp).
              stream().collect(Collectors.toMap(id->id, myService::getListForId));
    

    【讨论】:

      猜你喜欢
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-14
      • 2017-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多