Java 8 根据条件应用流过滤器

2022-01-22 00:00:00 java-8 java java-stream

在 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.

相关文章