我有以下表达:

scheduleIntervalContainers.stream()
        .filter(sic -> ((ScheduleIntervalContainer) sic).getStartTime() != ((ScheduleIntervalContainer)sic).getEndTime())
        .collect(Collectors.toList());

...其中scheduleIntervalContainers具有元素类型ScheduleContainer:
final List<ScheduleContainer> scheduleIntervalContainers

是否可以在过滤器之前检查类型?

最佳答案

您可以应用另一个filter以便仅保留ScheduleIntervalContainer实例,添加map将为您节省以后的转换:

scheduleIntervalContainers.stream()
    .filter(sc -> sc instanceof ScheduleIntervalContainer)
    .map (sc -> (ScheduleIntervalContainer) sc)
    .filter(sic -> sic.getStartTime() != sic.getEndTime())
    .collect(Collectors.toList());

或者,正如Holger所说,如果您喜欢那种样式,可以用方法引用替换lambda表达式:
scheduleIntervalContainers.stream()
    .filter(ScheduleIntervalContainer.class::isInstance)
    .map (ScheduleIntervalContainer.class::cast)
    .filter(sic -> sic.getStartTime() != sic.getEndTime())
    .collect(Collectors.toList());

关于java - 检查流中的instanceof,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35740543/

10-11 00:51