Java 8 流 - 将列表项转换为子类的类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35743525/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 17:04:49  来源:igfitidea点击:

Java 8 stream - cast list items to type of subclass

javajava-8

提问by quma

I have a list of ScheduleContainerobjects and in the stream each element should be casted to type ScheduleIntervalContainer. Is there a way of doing this?

我有一个ScheduleContainer对象列表,在流中每个元素都应该被转换为 type ScheduleIntervalContainer。有没有办法做到这一点?

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

采纳答案by Maciej Dobrowolski

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

回答by Peter Lawrey

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.

在性能说明上;第一个示例是一个非捕获 lambda,因此它不会创建任何垃圾,但第二个示例是一个捕获 lambda,因此可以在每次对其进行分类时创建一个对象。