ERR :
I have three Optional> which have to be combined and returned. I tried to use Optional.map()
and flatmap()
but was not successful.
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
}
Any thoughts on how to do is efficiently?
Naman :
Something like :
return Optional.of(Stream.of(entity1.orElse(new ArrayList<>()), entity2.orElse(new ArrayList<>()), entity3.orElse(new ArrayList<>()))
.flatMap(List::stream)
.collect(Collectors.toList()));
or rather more readable as :
return Optional.of(Stream.of(entity1, entity2, entity3)
.filter(Optional::isPresent)
.map(Optional::get)
.flatMap(List::stream)
.collect(Collectors.toList()));