Java 8 Applying stream filter based on a condition

后端 未结 2 1388
旧时难觅i
旧时难觅i 2020-12-31 00:10

In Java 8, is there a way to apply the filter on a stream based on a condition,

example

I have this stream

if (isAccessDisplayEnabled) {
             


        
2条回答
  •  独厮守ぢ
    2020-12-31 00:50

    One way to do it is

    Stream 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());
    

    another

     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.

    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.

提交回复
热议问题