Java 8 applies stream filters based on conditions

In Java 8, is there any way to apply filters to streams based on conditions,

example

I have this stream

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,searchString))
         .collect(Collectors.toList());
 }

I'm adding filters

On streams based on if else conditions There is no way to avoid if else, because if more filters appear, it will be difficult to maintain

please tell me

Solution

One way is

Stream<Source> stream = sourceMeta.getAllSources.parallelStream().map(x -> (Source)x);
if(isAccessDisplayEnabled) stream = stream.filter(s -> isAccessDisplayEnabled(s));
src = stream.filter(s - > containsAll(s,searchString))
            .collect(Collectors.toList());

the other one

src = sourceMeta.getAllSources.parallelStream().map(x -> (Source)x)
     .filter(isAccessDisplayEnabled? s - > isAccessDisplayEnabled(s): s -> true)
     .filter(s - > containsAll(s,searchString))
     .collect(Collectors.toList());

In either case, notice how a type conversion at the beginning simplifies the entire flow pipeline

Both solutions avoid re evaluating isaccessdisplayenabled for each flow element, but the second solution relies on the JVM's inline functionality – > > true when this code is critical to performance

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>