Java8流式转换列表项到子类的类型

Java8流式转换列表项到子类的类型,java,java-8,Java,Java 8,我有一个ScheduleContainer对象列表,在流中,每个元素都应该被强制转换为ScheduleIntervalContainer类型。有没有办法做到这一点 final List<ScheduleContainer> scheduleIntervalContainersReducedOfSameTimes final List<List<ScheduleContainer>> scheduleIntervalContainerOfCurrentDay

我有一个
ScheduleContainer
对象列表,在流中,每个元素都应该被强制转换为
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());
final List schedule intervalcontainers reducedofsametimes
最终列表scheduleIntervalContainerOfCurrentDay=新建ArrayList(
ScheduleIntervalContainers ReducedOfsametimes.stream()
.sorted(Comparator.comparing(ScheduleIntervalContainer::getStartDate).reversed())
.filter(s->s.getStartDate().WithTimeAtStarToDay().isEqual(today.WithTimeAtStarToDay()).collect(收集器
.groupingBy(ScheduleIntervalContainer::getStartDate,LinkedHashMap::new,Collectors.toList())
.values());

您的意思是要强制转换每个元素吗

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

在绩效说明上;第一个例子是一个非捕获lambda,所以它不会产生任何垃圾,但是第二个例子是捕获lambda,所以每次它被分类时都可以创建一个对象。

这是可能的,但是你应该首先考虑如果你需要一个铸造,或者只是函数应该从一开始就在子类类型上运行。 向下投射需要特别小心,您应该首先检查给定对象是否可以通过以下方式向下投射:

object instanceof ScheduleIntervalContainer
然后,您可以通过以下方式很好地投射它:

(ScheduleIntervalContainer) object
因此,整个流程应该如下所示:

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

这还不清楚。请发布一个。您在四小时前问了完全相同的问题。最简单的方法是使用方法引用:
.map(ScheduleIntervalContainer.class::cast)
,正如Jon Skeet在下面的评论中所建议的,以及在很久以后对OP提出的一个相关但不同的问题的回答中所建议的那样。方法引用在这里有效吗<代码>映射(ScheduleIntervalContainer.class::cast)将在我可以的时候亲自尝试。不确定它是否更具可读性,但我很感兴趣:)@JonSkeet我以前使用过它,但似乎不必要的聪明/晦涩.map(ScheduleIntervalContainer.class::cast)->这正是我需要的-谢谢!难道没有任何collect(像scala中一样)可以同时进行过滤和强制转换吗?
collection.stream()
    .filter(obj -> obj instanceof ScheduleIntervalContainer)
    .map(obj -> (ScheduleIntervalContainer) obj)
    // other operations