【问题标题】:Stream over an object array and collect to map with key as property and object as value在对象数组上流式传输并收集以将键作为属性和对象作为值进行映射
【发布时间】:2021-09-07 17:40:47
【问题描述】:

我有一个对象,Entity[],它具有像 Fields (Key:value) 这样的属性,所以要获取 field1 值,entity.getField(field1)。

我想创建一个地图

需要帮助通过 Arrays.stream().collect 使用 Collector, ,命令式方法如下:

Entity[] entityRecords; //array of Entity
Map<String, Entity> newMap = new HashMap<>(); 
for (Entity entityRecord : entityRecords) {
 newMap.put( entityRecord.getField(field), entityRecord);
 } 
return newMap;

【问题讨论】:

  • 更新帖子,详细说明您尝试过的方法以及遇到的问题
  • 你尝试了什么?使用 Streams API 几乎可以立即实现
  • Arrays.stream(entityRecords).collect(Collectors.toMap(Entity::getId, Function.identity())) 工作正常。但 Arrays.stream(entityRecords).collect(Collectors.toMap(Entity::getField(field1), Function.identity())) 没有。
  • 如果你确实有一个带参数的getter,你可以使用一个简单的lambda表达式Collectors.toMap(e -&gt; e.getField(field1), Function.identity())),但是这样的getter非常少见
  • @Eritrean 您也可以发布带有解释的答案,因为如果您不这样做,其他人会这样做。

标签: java java-8 java-stream


【解决方案1】:

这就是答案。我假设字段是实体中的一些属性

private Map<String, Entity> entityToMap() {
    String field = "Somefield";
    Entity[] entityRecords; //array of Entity
    return Arrays.stream(entityRecords)
           .collect(Collectors.toMap(e -> e.getField(field), Function.identity()));
}

【讨论】:

  • 是的,这行得通,当我尝试在 e 上执行 getField 时,我的 eclipse 显示错误,所以我没有继续进行,但后来它解决了。也很惊讶为什么它不起作用。谢谢大家。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-11
相关资源
最近更新 更多