Java 检查流中的instanceof
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35740543/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check instanceof in stream
提问by quma
I have the following expression:
我有以下表达式:
scheduleIntervalContainers.stream()
.filter(sic -> ((ScheduleIntervalContainer) sic).getStartTime() != ((ScheduleIntervalContainer)sic).getEndTime())
.collect(Collectors.toList());
...where scheduleIntervalContainers
has element type ScheduleContainer
:
...其中scheduleIntervalContainers
有元素类型ScheduleContainer
:
final List<ScheduleContainer> scheduleIntervalContainers
Is it possible to check the type before the filter?
是否可以在过滤器之前检查类型?
采纳答案by Eran
You can apply another filter
in order to keep only the ScheduleIntervalContainer
instances, and adding a map
will save you the later casts :
您可以应用另一个filter
以仅保留ScheduleIntervalContainer
实例,添加一个map
将为您节省以后的转换:
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:
或者,正如 Holger 评论的那样,如果您喜欢这种风格,您可以用方法引用替换 lambda 表达式:
scheduleIntervalContainers.stream()
.filter(ScheduleIntervalContainer.class::isInstance)
.map (ScheduleIntervalContainer.class::cast)
.filter(sic -> sic.getStartTime() != sic.getEndTime())
.collect(Collectors.toList());
回答by Ricardo Gasca
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() );
回答by Andrey
There is a small problem with @Eransolution - typing class name in both filter
and map
is error-prone - it is easy to forget to change the name of the class in both places. An improved solution would be something like this:
@Eran解决方案有一个小问题——在两个地方都输入类名filter
并且map
容易出错——很容易忘记在两个地方都改变类的名称。改进的解决方案将是这样的:
private static <T, R> Function<T, Stream<R>> select(Class<R> clazz) {
return e -> clazz.isInstance(e) ? Stream.of(clazz.cast(e)) : null;
}
scheduleIntervalContainers
.stream()
.flatMap(select(ScheduleIntervalContainer.class))
.filter( sic -> sic.getStartTime() != sic.getEndTime())
.collect(Collectors.toList());
However there might be a performance penalty in creating a Stream
for every matching element. Be careful to use it on huge data sets. I've learned this solution from @Tagir Vailev
但是,Stream
为每个匹配元素创建 a 可能会降低性能。在庞大的数据集上使用它时要小心。我从@ Tagir Vailev学到了这个解决方案