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.
我认为平面地图可能是解决方案,但我不知道如何在这里使用它。
2 个解决方案
#1
12
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());
}
#2
9
A Java 9 approach would be the folloing:
一个Java 9的方法是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.
也就是说,您应该避免使用选项作为参数,请参见这里。
#1
12
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());
}
#2
9
A Java 9 approach would be the folloing:
一个Java 9的方法是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.
也就是说,您应该避免使用选项作为参数,请参见这里。