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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With