Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 441
quma Avatar asked Mar 02 '16 07:03

quma


2 Answers

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()); 
like image 121
Eran Avatar answered Sep 17 '22 20:09

Eran


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() ); 
like image 22
Ricardo Gasca Avatar answered Sep 18 '22 20:09

Ricardo Gasca