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?
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());
A pretty elegant option is to use method reference of class:
scheduleIntervalContainers .stream() .filter( ScheduleIntervalContainer.class::isInstance ) .map( ScheduleIntervalContainer.class::cast ) .filter( sic -> sic.getStartTime() != sic.getEndTime()) .collect(Collectors.toList() );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With