Passing Multiple Arguments Into Stream Filter Predicates
Learn more about passing multiple arguments in Java.
Join the DZone community and get the full member experience.
Join For FreeWhen 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 BiPredicate
.
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.
public static class Predicates {
private String pattern;
public boolean containsPattern(String string) {
return string.contains(pattern);
}
public Predicates(String pattern) {
this.pattern = pattern;
}
}
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:
Predicates predicates = new Predicates("SSH");
System.getenv().keySet().stream().filter(predicates::containsPattern).collect(Collectors.toSet());
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.
Happy coding!
Opinions expressed by DZone contributors are their own.
Comments