I have an Optional
object that contains a list. I want to map each object in this list to another list, and return the resulting list.
That is:
public List<Bar> get(int id) {
Optional<Foo> optfoo = dao.getById(id);
return optfoo.map(foo -> foo.getBazList.stream().map(baz -> baz.getBar()))
}
Is there a clean way of doing that without having streams within streams?
I think that flatMap
might be the solution but I can't figure out how to use it here.
There isn't. flatMap
in case of Optional
is to flatten a possible Optional<Optional<T>>
to Optional<T>
. So this is correct.
public List<Bar> get(Optional<Foo> foo) {
return foo.map(x -> x.getBazList()
.stream()
.map(Baz::getBar)
.collect(Collectors.toList()))
.orElse(Collections.emptyList());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With