Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Passing Multiple Arguments Into Stream Filter Predicates

DZone 's Guide to

Passing Multiple Arguments Into Stream Filter Predicates

Learn more about passing multiple arguments in Java.

· Java Zone ·
Free Resource

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!

Topics:
java ,streams ,filter ,predicates ,tutorial ,standard api ,multiple arguments ,arguments

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}