Tuesday, January 29, 2019

Passing multiple arguments into stream filter predicates

When I am working with java streams I am intensively using filters to find objects. I offen have the situation where I'd like to pass two arguments to the fiter function. Unfortunately the standard API does only accept a Predicate but not BiPredicate.

To solve this limitation I define all my predicates as methods in a class, say Predicates. 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;
}
}
view raw Predicates.java hosted with ❤ by GitHub

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());

No comments:

Post a Comment