Java 连接可选列表
我有三个可选>必须合并并返回。我尝试使用Java 连接可选列表,java,java-8,optional,Java,Java 8,Optional,我有三个可选>必须合并并返回。我尝试使用Optional.map()和flatmap(),但没有成功 public Optional<List<Entiy>> getRecords() { Optional<List<Entiy>> entity1 = repo.findAllByStatus("1"); Optional<List<Entiy>> entity2 = repo.findAllByStatus
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
}
public可选getRecords(){
可选实体1=回购金融系统状态(“1”);
可选实体2=回购金融系统状态(“2”);
可选实体3=回购金融系统状态(“3”);
//需要返回entity1、2和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 Stream.of(entity1, entity2, entity3)
.filter(Optional::isPresent)
.map(Optional::get)
.flatMap(List::stream)
.collect(Collectors.collectingAndThen(Collectors.toList(), Optional::of));
重要的是要注意,此可选项永远不会为空。它将至少包含一个空列表,这违背了使用选项的目的。当使用集合
类型作为返回类型时,不会真正使用可选
,因为建议在使用空可选的集合时返回空集合
因此,我只需将方法的返回类型更改为
List
,并在不存在可选输入时让流返回空列表。我建议您不要从方法返回可选的列表。如果三个实体列表中的任何一个都没有记录,调用者只希望有一个空列表
public List<Entity> getRecords() {
return Stream.of("1", "2", "3")
.map(repo::findAllByStatus)
.flatMap(el -> el.map(List::stream).orElse(Stream.empty()))
.collect(Collectors.toList());
}
Collections.emptyList
您不需要对方法引用执行所有操作,有时候,lambda表达式并不坏,返回可选的.of(Stream.of(entity1,entity2,entity3).flatMap(o->o.map(List::Stream).orElse(null)).collect(Collectors.toList())代码>为什么要返回一个可选的?如果没有记录,打电话的人肯定会选择空列表?@OleV.V。确切地
public List<Entity> getRecords() {
return Stream.of("1", "2", "3")
.map(repo::findAllByStatus)
.flatMap(el -> el.map(List::stream).orElse(Stream.empty()))
.collect(Collectors.toList());
}
public List<Entity> getRecords() {
List<Entity> concatenation = new ArrayList<>();
repo.findAllByStatus("1").ifPresent(concatenation::addAll);
repo.findAllByStatus("2").ifPresent(concatenation::addAll);
repo.findAllByStatus("3").ifPresent(concatenation::addAll);
return concatenation;
}