This week at work a colleague showed a nice feature of the Pattern
class in Java: we can easily turn a Pattern
into a Predicate
with the asPredicate
and asMatchPredicate
methods. The asPredicate
method return a predicate for testing if the pattern can be found given string. And the asMatchPredicate
return a predicate for testing if the pattern matches a given string.
In the following example code we use both methods to create predicates:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | package mrhaki; import java.util.List; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; public class PatternPredicate { public static void main(String[] args) { // Sample pattern. var pattern = Pattern.compile( "J" ); // asPredicate returns a predicate to test if // the pattern can be found in the given string. assert pattern.asPredicate().test( "Java" ); assert !pattern.asPredicate().test( "Groovy" ); // asMatchPredicate returns a predicate to test if // the pattern completely matches the given string. assert pattern.asMatchPredicate().test( "J" ); assert !pattern.asMatchPredicate().test( "Java" ); // Using the asPredicate and asMatchPredicate is very // useful with the streams API. var languagesWithJ = Stream.of( "Java" , "Groovy" , "Clojure" , "JRuby" , "JPython" ) .filter(pattern.asPredicate()) .collect(Collectors.toList()); assert languagesWithJ.size() == 3 ; assert languagesWithJ.equals(List.of( "Java" , "JRuby" , "JPython" )); var startsWith_J_EndsWith_y = Pattern.compile( "^J\\w+y$" ).asMatchPredicate(); var languagesWithJy = Stream.of( "Java" , "Groovy" , "Clojure" , "JRuby" , "JPython" ) .filter(startsWith_J_EndsWith_y) .collect(Collectors.toList()); assert languagesWithJy.size() == 1 ; assert languagesWithJy.equals(List.of( "JRuby" )); } } |
Written with Java 13.