本文介绍了检查流中的instanceof的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我有以下表达式:

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

...其中 scheduleIntervalContainers 具有元素类型 ScheduleContainer

...where scheduleIntervalContainers has element type ScheduleContainer:

final List<ScheduleContainer> scheduleIntervalContainers

是否可以在过滤器之前检查类型?

Is it possible to check the type before the filter?

推荐答案

您可以应用另一个过滤器,以便只保留 ScheduleIntervalContainer 实例,并添加地图将为您节省以后的演员表:

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

或者,正如Holger所评论的,如果您喜欢该样式,可以用方法引用替换lambda表达式:

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

这篇关于检查流中的instanceof的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 23:01