我有三个 Optional> 必须合并并返回。我尝试使用 Optional.map()
和 flatmap()
但没有成功。
public Optional<List<Entiy>> getRecords() {
Optional<List<Entiy>> entity1 = repo.findAllByStatus("1");
Optional<List<Entiy>> entity2 = repo.findAllByStatus("2");
Optional<List<Entiy>> entity3 = repo.findAllByStatus("3");
//Need to return a concatenation of entity1, 2 and 3
}
关于如何高效地做事有什么想法吗?
最佳答案
类似的东西:
return Optional.of(Stream.of(entity1.orElse(new ArrayList<>()), entity2.orElse(new ArrayList<>()), entity3.orElse(new ArrayList<>()))
.flatMap(List::stream)
.collect(Collectors.toList()));
或者说更具可读性:
return Optional.of(Stream.of(entity1, entity2, entity3)
.filter(Optional::isPresent)
.map(Optional::get)
.flatMap(List::stream)
.collect(Collectors.toList()));
关于java - 连接可选列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55186324/