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?
The easiest I can think of is:
Stream<X> stream1 = ...
Stream<SubClassA> stream2 = stream1.map(SubClassA.class::cast);
Use generic 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.