我有三个Optional>,必须将它们组合并返回。我尝试使用Optional.map()
and 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()));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)