Search code examples
javajava-8java-streaminstanceof

Check instanceof in stream


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

Is it possible to check the type before the filter?


Solution

  • Not exactly a stream, but Guava's FluentIterable does this very cleanly:

    FluentIterable.from(scheduleIntervalContainers)
            .filter(ScheduleIntervalContainer.class)
            .filter(sic -> sic.getStartTime() != sic.getEndTime())
            .toList();