Check instanceof in stream

前端 未结 3 1839
孤城傲影
孤城傲影 2021-01-30 09:51

I have the following expression:

scheduleIntervalContainers.stream()
        .filter(sic -> ((ScheduleIntervalContainer) sic).getStartTime() != ((ScheduleInte         


        
3条回答
  •  故里飘歌
    2021-01-30 10:51

    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());
    

提交回复
热议问题