Search

Dark theme | Light theme

February 28, 2020

Java Joy: Turn A Pattern Into A Predicate

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:

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.