Java 可选<List<T>> 到地图转换

Java Optional<List<T>> to Map conversion

我有一段这样的代码:

    public Map<String, Details> getAllDetails(final String name) {
        Optional<List<JobExecution>> allJobExecutionsByName = Optional.ofNullable(jobExecutionDao.getAllJobExecutionsByName(name));

//        return allJobExecutionsByName.map(x -> x.stream()
//                                                    .map(execution -> Pair.of(getJobParam(execution, "id"), getDetailsFromExecution(execution)))
//                                                    .collect(toList()))
//                                         .orElse(emptyList());

    }

我想 return Map<String, Details>

而不是 returning List<Pair<String, Details>>

如何将 Optional<List<JobExecution>> 转换为键为 id 且值为 Detail 对象的映射?

您可以使用Collector.toMap收集为地图

return allJobExecutionsByName.map(x -> 
          x.stream()
           .collect(Collector.toMap(e -> getJobParam(e, "id"),
                                    e -> getDetailsFromExecution(e))))
       .orElse(Collections.emptyMap());

现有答案建议您可以使用 Collectors.toMap,但另外根据标签,您 不应在当前上下文 中使用 Optional

public Map<String, Details> getAllDetails(final String name) {
    List<JobExecution>> allJobExecutionsByName = jobExecutionDao.getAllJobExecutionsByName(name);
    
    // perform below check only if you cannot control the returned value above
    if(allJobExecutionsByName == null) return Collections.emptyMap();
    
    return allJobExecutionsByName.stream()
                .collect(Collector.toMap(e -> getJobParam(e, "id"),
                                     e -> getDetailsFromExecution(e))));
}

如果您的列表为空,只需 return 空列表并继续流式传输空列表。

allJobExecutionsByName.orElse(Collections.emptyList())
    .stream()
    .collect(Collectors.toMap(
        (e -> getJobParam(e, "id"),
        e -> getDetailsFromExecution(e))
    ));

我遇到了这个问题,所以我做了这样的事情:

    public Map<String, Details> getAllDetails(final String name) {
        return Optional.ofNullable(jobExecutionDao.getAllJobExecutionsByName(name))
                .map(x -> x.stream()
                .collect(Collector.toMap(e -> getJobParam(e, "id"), e -> getDetailsFromExecution(e)))
                .orElse(Collections.emptyMap());
    }