Java 8 stream - cast list items to type of subclass

好久不见. 提交于 2020-02-26 13:04:40

问题


I have a list of ScheduleContainer objects and in the stream each element should be casted to type ScheduleIntervalContainer. Is there a 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());

回答1:


It's possible, but you should first consider if you need casting at all or just the function should operate on subclass type from the very beginning.

Downcasting requires special care and you should first check if given object can be casted down by:

object instanceof ScheduleIntervalContainer

Then you can cast it nicely by:

(ScheduleIntervalContainer) object

So, the whole flow should look like:

collection.stream()
    .filter(obj -> obj instanceof ScheduleIntervalContainer)
    .map(obj -> (ScheduleIntervalContainer) obj)
    // other operations



回答2:


Do you mean you want to cast each element?

scheduleIntervalContainersReducedOfSameTimes.stream()
                                            .map(sic -> (ScheduleIntervalContainer) sic)
                // now I have a Stream<ScheduleIntervalContainer>

Or you could use a method reference if you feel it is clearer

                                            .map(ScheduleIntervalContainer.class::cast)

On a performance note; the first example is a non-capturing lambda so it doesn't create any garbage, but the second example is a capturing lambda so could create an object each time it is classed.



来源:https://stackoverflow.com/questions/35743525/java-8-stream-cast-list-items-to-type-of-subclass

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!