Sheldon Wei
Sheldon Wei

Reputation: 1252

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.

Upvotes: 2

Views: 9242

Answers (3)

dsncode
dsncode

Reputation: 2441

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);
    }
 }

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201409

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.

Upvotes: 3

Jigar Joshi
Jigar Joshi

Reputation: 240860

.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`)
}

Upvotes: 1

Related Questions