Lambda-fied pattern matching

Dan Smith daniel.smith at oracle.com
Wed Nov 19 21:54:28 UTC 2014


Working with the pattern matching API, I noticed that it could be made a lot less clumsy with some lambdafication.

Here's the status quo:

Pattern p = Pattern.compile("(\w)*, (\d)*, (\w)*");
for (String s : lines) {
    Matcher m = p.matcher(str);
    if (m.match(s)) {
        System.out.println(m.group(1));
    }
}

With a lambda-friendly API:

Pattern p = Pattern.compile("\d*, \d*, \d*");
for (String s : lines) {
    p.match(str, r -> System.out.println(r.group(1)));
}

The 'match' is declared as 'match(String, Consumer<MatchResult>)'.  You could argue that the functional interface should be a Function rather than a Consumer; whatever.

Could also do 'matchFirst', 'matchAll' -- the latter eliminates even more boilerplate.

If considered useful, this could be added to String too:

str.match("\d*, \d*, \d*", r -> System.out.println(r.group(1)));

Is this something that has been considered?  Should I file an RFE?

—Dan


More information about the core-libs-dev mailing list