Recently I change version of the JDK 8 instead 7 of my project and now I overwrite some code snippets using new features that came with Java 8.
final Matcher
Marko's answer demonstrates how to get matches into a stream using a Spliterator
. Well done, give that man a big +1! Seriously, make sure you upvote his answer before you even consider upvoting this one, since this one is entirely derivative of his.
I have only a small bit to add to Marko's answer, which is that instead of representing the matches as an array of strings (with each array element representing a match group), the matches are better represented as a MatchResult
which is a type invented for this purpose. Thus the result would be a Stream
instead of Stream
. The code gets a little simpler, too. The tryAdvance
code would be
if (m.find()) {
action.accept(m.toMatchResult());
return true;
} else {
return false;
}
The map
call in his email-matching example would change to
.map(mr -> mr.group(2))
and the OP's example would be rewritten as
Set set = matcherStream(mtr)
.map(mr -> mr.group(0).toLowerCase())
.collect(toSet());
Using MatchResult
gives a bit more flexibility in that it also provides offsets of match groups within the string, which could be useful for certain applications.