检查流中的 instanceofinstanceof

2023-09-07 01:26:33 作者:跪下、叫帅哥

I have the following expression:

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

...where scheduleIntervalContainers has element type ScheduleContainer:

final List<ScheduleContainer> scheduleIntervalContainers
JavaScript中的instanceof的检验原理

Is it possible to check the type before the filter?

解决方案

You can apply another filter in order to keep only the ScheduleIntervalContainer instances, and adding a map will save you the later casts :

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

Or, as Holger commented, you can replace the lambda expressions with method references if you prefer that style:

scheduleIntervalContainers.stream()
    .filter(ScheduleIntervalContainer.class::isInstance)
    .map (ScheduleIntervalContainer.class::cast)
    .filter(sic -> sic.getStartTime() != sic.getEndTime())
    .collect(Collectors.toList());