Java 8 stream - cast list items to typ of subclass -
this question has answer here:
- java 8 stream - check if instanceof 3 answers
i have list of schedulecontainer types , ins stream each element should casted type scheduleintervalcontainer. there way of doing this?
final list<schedulecontainer> scheduleintervalcontainersreducedofsametimes final list<list<schedulecontainer>> scheduleintervalcontainerofcurrentday = new arraylist<>( scheduleintervalcontainersreducedofsametimes.stream() .sorted(comparator.comparing(scheduleintervalcontainer::getstartdate).reversed()) .filter(s -> s.getstartdate().withtimeatstartofday().isequal(today.withtimeatstartofday())).collect(collectors .groupingby(scheduleintervalcontainer::getstartdate, linkedhashmap::new, collectors.<schedulecontainer> tolist())) .values());
it's possible, should first consider if need casting @ or function should operate on subclass type beginning.
downcasting requires special care , should first check if given object can casted down by:
object instanceof scheduleintervalcontainer
then can cast nicely by:
(scheduleintervalcontainer) object
so, whole flow should like:
collection.stream() .filter(obj -> obj instanceof scheduleintervalcontainer) .map(obj -> (scheduleintervalcontainer) obj) // other operations
Comments
Post a Comment