在对象数组上流式传输并收集以使用键作为 属性 和对象作为值进行映射

Stream over an object array and collect to map with key as property and object as value

我有一个对象 Entity[],它具有 Fields (Key:value) 等属性,因此要获取 field1 值,entity.getField(field1).

我想创建一个地图

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

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

答案在这里。我假设字段是一些 属性 in entity

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()));
}