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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Predicates predicates = new Predicates("SSH"); | |
System.getenv().keySet().stream().filter(predicates::containsPattern).collect(Collectors.toSet()); |
No comments:
Post a Comment