Passing Multiple Arguments Into Stream Filter Predicates

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 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!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s