Java 8 Applying stream filter based on a condition(Java 8 根据条件应用流过滤器)
问题描述
在 Java 8 中,有没有办法根据条件在流上应用过滤器,
In Java 8, is there a way to apply the filter on a stream based on a condition,
例子
我有这个直播
if (isAccessDisplayEnabled) {
src = (List < Source > ) sourceMeta.getAllSources.parallelStream()
.filter(k - > isAccessDisplayEnabled((Source) k))
.filter(k - > containsAll((Source) k, substrings, searchString))
.collect(Collectors.toList());
} else {
src = (List < Source > ) sourceMeta.getAllSources.parallelStream()
.filter(k - > containsAll((Source) k, substrings, searchString))
.collect(Collectors.toList());
}
我正在添加过滤器
.filter(k - > isAccessDisplayEnabled((Source) k)))
基于 if-else 条件的流.有没有办法避免 if-else,因为如果有更多的过滤器出现,那么它将很难维护.
on the stream based on the if-else condition. Is there a way to avoid that if-else, since if there are more filters coming up,then it will be hard to maintain.
请告诉我
推荐答案
一种方法是
Stream<Source> stream = sourceMeta.getAllSources.parallelStream().map(x -> (Source)x);
if(isAccessDisplayEnabled) stream = stream.filter(s -> isAccessDisplayEnabled(s));
src = stream.filter(s - > containsAll(s, substrings, searchString))
.collect(Collectors.toList());
另一个
src = sourceMeta.getAllSources.parallelStream().map(x -> (Source)x)
.filter(isAccessDisplayEnabled? s - > isAccessDisplayEnabled(s): s -> true)
.filter(s - > containsAll(s, substrings, searchString))
.collect(Collectors.toList());
在任何一种情况下,请注意在开头执行一种类型转换如何简化整个流管道.
In either case, note how performing one type cast at the beginning simplifies the entire stream pipline.
这两种解决方案都避免为每个流元素重新评估 isAccessDisplayEnabled
,但是,第二种方法依赖于 JVM 内联 s -> 的能力.当此代码对性能至关重要时,为 true
.
Both solutions avoid re-evaluating isAccessDisplayEnabled
for every stream element, however, the second relies on the JVM’s capability of inlining s -> true
when this code turns out to be performance critical.
这篇关于Java 8 根据条件应用流过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java 8 根据条件应用流过滤器
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- 转换 ldap 日期 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 获取数字的最后一位 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01