java可选< list< t>>Map转换

xpszyzbs  于 2021-07-05  发布在  Java
关注(0)|答案(4)|浏览(284)

我有这样一段代码:

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

    }

而不是回来 List<Pair<String, Details>> ,我想回去 Map<String, Details> 我如何转换 Optional<List<JobExecution>> 一张Map的钥匙是 id 价值就是 Detail 反对?

pxq42qpu

pxq42qpu1#

如果列表为空,只需返回空列表并继续流式传输空列表。

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

oknrviil2#

我经历了这个问题,所以我做了这样的事情:

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

fhity93d3#

你可以用 Collector.toMap 作为Map收集

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

pbwdgjma4#

现有的答案表明你可以使用 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))));
}

相关问题