繁体   English   中英

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

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

我有一个包含列表的Optional对象。 我想将此列表中的每个对象映射到另一个列表,并返回结果列表。

那是:

public List<Bar> get(int id) {
    Optional<Foo> optfoo = dao.getById(id);
    return optfoo.map(foo -> foo.getBazList.stream().map(baz -> baz.getBar()))
}

如果没有溪流内的溪流,有没有一种干净的方式呢?

我认为flatMap可能是解决方案,但我无法弄清楚如何在这里使用它。

没有。 如果是OptionalflatMap将可能的Optional<Optional<T>>压平为Optional<T> 所以这是正确的。

public List<Bar> get(Optional<Foo> foo) {
     return foo.map(x -> x.getBazList()
                          .stream()
                          .map(Baz::getBar)
                          .collect(Collectors.toList()))
               .orElse(Collections.emptyList());
}

Java 9方法将成为下列方法:

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

也就是说,您应该避免使用Optional s作为参数, 请参阅此处

暂无
暂无

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

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