假设我有一个名为 Importable
的界面它有多种实现,其中之一是 ImportableImpl
.
我有一个类的列表 Staging
它有一个通用类型: Importable
.
通过java 8流,我想转换列表:
List<Staging<Importable>> list1
到列表:
List<Staging<ImportableImpl>> list2
我已经确定列表 list1
是 Staging<ImportableImpl>
的列表,所以没有 ClassCastException
可能会发生。
不知道java是否授权这种泛型类型的转换。
我想尝试这样的事情:
list1.stream()
.map(Staging::getImportable) // retrieve generic type
.map(ImportableImpl.class::cast)
.collect(Collectors.toList())
但这样我会得到一个 List<ImportableImpl>
而不是List<Staging<ImportableImpl>>
.
最佳答案
我真的不明白你的尝试的目的是什么,但你不被允许转List<Staging<Importable>>
到 List<Staging<ImportableImpl>>
无论第一个列表中有什么。这些类型是不可转换的。
唯一合理的方法(尽管有警告)是:
@SuppressWarnings("unchecked") // if you are sure that all elements are ImportableImpl
list.stream().map(i -> (Staging<ImportableImpl>) i).collect(Collectors.toList());
其中list
类型为 List<Staging<? extends Importable>>
,不是List<Staging<Importable>>
.
当然可以写成方法引用:
list.stream().map(Staging.class::<ImportableImpl>cast).collect(Collectors.toList());
关于java - 使用 java 8 流将 List<Staging<Importable>> 转换为 List<Staging<ImportableImpl>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40936301/