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

qum*_*uma 7 java java-8

我有一个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());
Run Code Online (Sandbox Code Playgroud)

Mac*_*ski 28

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

向下转换需要特别小心,您应首先检查给定的对象是否可以通过以下方式进行转换:

object instanceof ScheduleIntervalContainer
Run Code Online (Sandbox Code Playgroud)

然后你可以通过以下方式很好地施展它:

(ScheduleIntervalContainer) object
Run Code Online (Sandbox Code Playgroud)

所以,整个流程应如下所示:

collection.stream()
    .filter(obj -> obj instanceof ScheduleIntervalContainer)
    .map(obj -> (ScheduleIntervalContainer) obj)
    // other operations
Run Code Online (Sandbox Code Playgroud)


Pet*_*rey 22

你的意思是你想要投射每个元素吗?

scheduleIntervalContainersReducedOfSameTimes.stream()
                                            .map(sic -> (ScheduleIntervalContainer) sic)
                // now I have a Stream<ScheduleIntervalContainer>
Run Code Online (Sandbox Code Playgroud)

或者,如果您觉得它更清晰,您可以使用方法参考

                                            .map(ScheduleIntervalContainer.class::cast)
Run Code Online (Sandbox Code Playgroud)

在表演笔记上; 第一个例子是非捕获lambda,因此它不会产生任何垃圾,但第二个例子是捕获lambda,因此每次分类时都可以创建一个对象.

  • 方法参考会在这里工作吗?`map(ScheduleIntervalContainer.class :: cast)`我会尽我所能.不确定它更具可读性,但我很感兴趣:) (5认同)