Java 8流-将列表项转换为子类的类型 [英] Java 8 stream - cast list items to type of subclass

查看:904
本文介绍了Java 8流-将列表项转换为子类的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ScheduleContainer对象的列表,并且在流中,每个元素都应强制转换为ScheduleIntervalContainer类型.有没有办法做到这一点?

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());

推荐答案

这是可能的,但是您应该首先考虑是否完全需要强制转换,或者仅从一开始就应该对子类类型进行操作.

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

这篇关于Java 8流-将列表项转换为子类的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆