Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to (dynamically) change Java stream's filter conditions?

I have a few classes of the following general form, where this.words is a List<String> containing one word per element:

public ArrayList<String> wordsInclZ() {
    ArrayList<String> results = new ArrayList<>();

    this.words.stream()
        .filter(word -> word.contains("z"))
        .forEach(word -> results.add(word));

    return results;
}

The only bit I have to change are the filter conditions, i.e., the expression inside .filter(). This doesn't appear to be a terrible copy-paste situation, however I'd like to learn if it was possible to write neater code.

Is there a concise way to generalize this functionality? I guess I'm basically asking can I and how should I pass the lambda to the .filter() as a parameter of a general method that handles the rest of the above method's functionality.

like image 310
basse Avatar asked Mar 10 '23 16:03

basse


1 Answers

You can create a parameter for your function:

Predicate<String> predicate

You can then pass the filter to your function:

wordsInclZ(word -> word.contains("z"));

And the filter would be:

filter(predicate);
like image 170
john16384 Avatar answered Mar 16 '23 21:03

john16384