When I am working with Java streams, I am intensively using filters to find objects. I often encounter the situation where I’d like to pass two arguments to the fiter function. But, unfortunately, the standard API only accepts a
Predicate and not
To solve this limitation, I define all of my predicates as methods in a class, for example,
Predicates. Then, that predicate class takes a constant parameter.
When I am using the
Predicates, I instintiate an instance with the constant parameter of my choice. Then, I can use the instance methods as method references passed to the filter, like so:
This way, you can easily pass additional parameters to the filter, and your code is easy to read, even if you have multiple filters in the chain. Also, you can reuse the predicates in the
Predicate class in other Collection operations.