[英]Is there a specific aggregate operation to map superclasses to subclasses?
Is there a specific aggregate operation to map superclasses to subclasses? 是否存在用于将超类映射到子类的特定聚合操作?
I frequently find myself doing operations such as: 我经常发现自己正在执行以下操作:
list
.stream()
.map((A element) -> (SubClassA) element);
Is there an operation that does the equivalent of the map
function above, that is, takes a Stream
of values and casts them to a subclass? 是否存在与上述
map
函数等效的操作,即采用值Stream
并将其强制转换为子类?
The easiest I can think of is: 我最容易想到的是:
Stream<X> stream1 = ...
Stream<SubClassA> stream2 = stream1.map(SubClassA.class::cast);
Use generic wirldcard. 使用通用的wirldcard。
List<A> list = new ArrayList<>();
Stream<A> streamA1 = list.stream();
Stream<B> streamB1 = (Stream<B>)streamA1; // ERROR! Cannot cast from Stream<A> to Stream<B>
Stream<? extends A> streamA2 = list.stream();
Stream<B> streamB2 = (Stream<B>)streamA2; // OK
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.