简体   繁体   English

在Java中从Optional-> List-> List转换的链方法

[英]Chain methods to convert from Optional->List->List in Java

I have an Optional object that contains a list. 我有一个包含列表的Optional对象。 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. 我认为flatMap可能是解决方案,但我无法弄清楚如何在这里使用它。

There isn't. 没有。 flatMap in case of Optional is to flatten a possible Optional<Optional<T>> to Optional<T> . 如果是OptionalflatMap将可能的Optional<Optional<T>>压平为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: Java 9方法将成为下列方法:

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 . 也就是说,您应该避免使用Optional s作为参数, 请参阅此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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