Java 8 根据条件应用流过滤器 [英] Java 8 Applying stream filter based on a condition

查看:34
本文介绍了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 根据条件应用流过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆