Jordan Mackie
Jordan Mackie

Reputation: 2406

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.

Upvotes: 15

Views: 15594

Answers (2)

Ousmane D.
Ousmane D.

Reputation: 56423

A Java 9 approach would be the folloing:

public List<Bar> get(Optional<Foo> foo) {
         return foo.map(Foo::getBazList)
                   .stream()
                   .flatMap(Collection::stream)
                   .map(Baz::getBar)
                   .collect(Collectors.toList());
}

That said, you should avoid using Optionals as parameters, see here.

Upvotes: 10

Eugene
Eugene

Reputation: 120848

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());
}

Upvotes: 17

Related Questions