从 Optional<> 投射到 ArrayList<> [英] Cast from Optional<> to ArrayList<>
问题描述
我有以下情况:
public ArrayList<A> getMethods(){
return b.c.test();
}
所以,我的问题是 b.c.test()
返回一个带有 Optional
作为返回类型的值.但我需要返回一个 ArrayList
.
So, my problem is that b.c.test()
returns a value with Optional<A>
as return type. But I need to return an ArrayList<A>
.
所以,我尝试将其转换为:
So, I tried to cast it and rewrite it to :
public ArrayList<A> getMethods(){
return (ArrayList<A>)b.c.test();
}
但是 Eclipse 说从 Optional
到 ArrayList
的这种转换是不可能的.
But Eclipse says that such a cast from Optional<A>
to ArrayList<A>
is not possible.
我该如何解决这个问题?
How can I solve this problem?
推荐答案
我假设您的预期语义是如果该值存在,则返回一个包含单个项目的列表,否则返回一个空列表."在这种情况下,我会建议如下:
I am presuming your intended semantic is 'if the value is present return a list with a single item, otherwise return an empty list.' In that case I would suggest something like the following:
ArrayList<A> result = new ArrayList<>();
b.c.test().ifPresent(result::add);
return result;
但是我建议你的返回类型应该是 List
而不是 ArrayList
因为这让你有机会改变列表的类型而不改变来电者.如果不存在可选值,它还允许您返回 Collections.EMPTY_LIST
,这比创建不必要的 ArrayList
更有效.
However I would suggest your return type should be List<A>
rather than ArrayList<A>
as that gives you the opportunity to change the type of list without changing the callers. It would also allow you to return Collections.EMPTY_LIST
if the optional value is not present which is more efficient than creating an unnecessary ArrayList
.
更新:Java 9 现在有一个更简单的选择:
Update: there's now an easier option with Java 9:
b.c.test().stream().collect(Collectors.toList());
更新:Java 16 中更简单的选项:
Update: and even easier option with Java 16:
b.c.test().stream().toList();
这篇关于从 Optional<> 投射到 ArrayList<>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!