[英]Java Optional - How to convert one type of list to another
I have an optional Optional<TypeA>
from which I can do a map
function and get Optional<List<TypeB>>
.我有一个可选的
Optional<TypeA>
,我可以从中执行map
function 并获得Optional<List<TypeB>>
。
But I would like to now map it to Optional<List<TypeC>>
and then orElse()
it.但我想现在 map 到
Optional<List<TypeC>>
然后orElse()
它。 So putting in pseudo code所以输入伪代码
Optional.ofNullable(fooReturnsTypeA()).map(TypeA::barReturnsListTypeB()).{?}.orElse(new ArrayList<TypeC>());
I know how to use map
function, but it's been a while dealing with Optional
with map
.我知道如何使用
map
function,但是用map
处理Optional
已经有一段时间了。 So, I might be just staring at the answer.所以,我可能只是盯着答案看。 Could someone help me with
{?}
part?有人可以帮我解决
{?}
部分吗?
Regards,问候,
What about this?那这个呢?
Optional.ofNullable(fooReturnsTypeA())
.map(TypeA::barReturnsListTypeB())
.map(typeBList->typeBList
.stream()
.map(TypeB::barReturnsTypeC)
.collect(Collectors.toList())
)
.orElse(new ArrayList<TypeC>())
This basically creates a new Stream
in .map
and uses it to convert all elements of TypeB
to TypeC
(assuming TypeB
has a method barReturnsTypeC
without parameters that returns an instance of TypeC
).这基本上在
.map
Stream
使用它将TypeB
的所有元素转换为TypeC
(假设TypeB
有一个方法barReturnsTypeC
没有返回TypeC
实例的参数)。
You can use another map
and write method to convert List<TypeB>
to List<TypeC>
.您可以使用另一个
map
和 write 方法将List<TypeB>
转换为List<TypeC>
。
You're code will look like this:您的代码将如下所示:
Optional.ofNullable(fooReturnsTypeA())
.map(TypeA::barReturnsListTypeB())
.map(this::convert)
.orElse(new ArrayList<TypeC>());
And your method to convert:以及您的转换方法:
private List<TypeC> convert(List<TypeB> list) {
// conversion logic
// return List<TypeC>
}
First, I would replace the orElse
with orElseGet
.首先,我会将
orElse
替换为orElseGet
。 Depending on your code, using orElseGet
instead of orElse
can improve your performance.根据您的代码,使用
orElseGet
而不是orElse
可以提高性能。 The parameter of orElse
is evaluated even when the Optional
is non-empty.即使
Optional
不为空,也会评估orElse
的参数。 On the other hand, the parameter of orElseGet
is evaluated only when the Optional
is empty.另一方面,仅当
Optional
为空时才评估orElseGet
的参数。 In your specific case, you may be instantiating unnecessary ArrayList
s.在您的特定情况下,您可能正在实例化不必要的
ArrayList
s。 From the Javadoc:来自 Javadoc:
Supplier method passed as an argument is only executed when an Optional value is not present.
作为参数传递的供应商方法仅在不存在 Optional 值时执行。
You can also dismiss the {?}
by using a stream
in the map
.您还可以通过在
map
中使用stream
来关闭{?}
。
Optional.ofNullable(fooReturnsTypeA())
.map(typeA -> typeA.barReturnsListTypeB().stream()
.map(TypeB::barReturnsTypeC).collect(Collectors.toList()))
.orElseGet(() -> new ArrayList<TypeC>());
Note: see this for more information about the difference between orElse
and orElseGet
.注意:有关
orElse
和orElseGet
之间区别的更多信息,请参阅 此。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.