【发布时间】:2017-06-05 17:28:13
【问题描述】:
我有两个类:
public class A {
//attibutes and methods
}
public class B extends A {
//atributes and methods
}
现在我有一个服务,它返回一个 List 元素类型为 A。让我们称之为 generateAElements();
我想调用那个方法,过滤得到的List只保留 B 类型的元素,它们也是 A 类型。
List<A> listA = generateAElements();
List<A> listAA = listA.filter( p -> p instanceof B).collect(Collectors.toList());
List<B> listB = new ArrayList<>();
// need to create a new list, iterate overListA and add elements of type B?
for (A itemA : listA) {
listB.add((B) itemA);
}
有没有一种有效的方法来做到这一点?
重要提示:列表可能包含大量元素。
【问题讨论】:
-
您不能从
List<A>转换为List<B>,因为它们与继承无关。 -
@JarrodRoberson - 这不是那个问题的重复 - OP 没有询问多态行为。
标签: java list casting java-8 java-stream