I have three Optional> which have to be combined and returned. I tried to use Optional.map()
and flatmap()
but was not successful.
It gets easier when you use a stream:
return Stream.of(entity1, entity2, entity3)
.filter(Optional::isPresent)
.map(Optional::get)
.flatMap(List::stream)
.collect(Collectors.collectingAndThen(Collectors.toList(), Optional::of));
Important to note that this optional won't ever be empty. It will contain at least an empty list, which defeats the purpose of using optionals. When using Collection
types as return types, Optional
are not really used because it's recommended to return an empty collection where an empty optional would be used.
So I would just change the method's return type to List
and let the stream return an empty list when no input optional is present.