Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chain methods to convert from Optional->List->List in Java

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.

like image 539
Jordan Mackie Avatar asked Jun 13 '18 20:06

Jordan Mackie


1 Answers

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());
}
like image 125
Eugene Avatar answered Sep 20 '22 17:09

Eugene