Java 8 Applying stream filter based on a condition

后端 未结 2 1394
旧时难觅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:35

    Your condition has the same name as your method. I'm going to assume you meant for those to be different, so let's say it was this:

    if (someCondition) {
        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());
    }
    

    If you want to remove the if/else, you can instead perform the check in the first filter:

    src = (List < Source > ) sourceMeta.getAllSources.parallelStream()
        .filter(k - > !someCondition || isAccessDisplayEnabled((Source) k))
        .filter(k - > containsAll((Source) k, substrings, searchString))
        .collect(Collectors.toList());
    

    In the else case, you take everything and remove the isAccessDisplayEnabled() method call, so the condition is effectively "if someCondition is false or isAccessDisplayEnabled(k)". If someCondition comes out false, then the isAccessDisplayEnabled() check is skipped.

提交回复
热议问题