简体   繁体   中英

How to use java8 stream filter() method under condition?

I wonder how to choose to use stream filter under condition. That is, whether I can use fiter or not decided by a variable.

My original codes are:

if (keyword == null) {
        return list.parallelStream()
            //not using filter
            .map(...)
            .collect(Collectors.toList());
    }
    return list.parallelStream()
            .filter(dto -> dto.getString().contains(keyword))
            .map(...)
            .collect(Collectors.toList());

So can I mix the two return statements into one? Like

return list.parallelStream()
            .filterIfKeywordNonNull(dto -> dto.getString().contains(keyword))
            .map(...)
            .collect(Collectors.toList());

Thank you in advance.

You could simply add the keyword test to your filter. Like,

return list.parallelStream()
        .filter(dto -> keyword == null || dto.getString().contains(keyword))
        .map(...)
        .collect(Collectors.toList());

For improved efficiency, it's also possible to build the Stream once and save it a temporary variable using a ternary. Like,

Stream<T> stream = (keyword == null) ? list.parallelStream() :
    list.parallelStream().filter(dto -> dto.getString().contains(keyword));
return stream.map(...).collect(Collectors.toList());

You could use the ternary in the return, but then you have to repeat the map and collect calls.

.filter(getFilter(dto));

and

private static Predicate getFilter(String dto){
 // logic here. either return Filter A's singleton instance or return Null filter (that allows to pass everything i.e. `(dto)-> true`)
}

since filter is not a ending stream condition. you could add it at anytime. so, how about this?

public class ConditionalStreams {

//send your stream, a boolean, and the filter condition
public static Stream<Integer> filterFun(Stream<Integer> stream, boolean needToFilter, Predicate<Integer> filterStream){
        if(needToFilter)
            return stream.filter(filterStream);
        else
            return stream;
    }

public static void main(String[] args) {
    List<Integer> numbers = Arrays.asList(1,2,3,4,5,6);

    // create your filter condition
    Predicate<Integer> filterStream = (num)->num%2==0;

    System.out.println("without filter: ");
    //call the function, pass parameters and return the right stream and process it.
    filterFun(numbers.parallelStream(),false,filterStream)
    .forEach(System.out::println);

    System.out.println("with filter : ");
    filterFun(numbers.parallelStream(),true,filterStream)
    .forEach(System.out::println);
    }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM