简体   繁体   中英

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.

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

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 Optional s as parameters, see here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM