1

Trying to understand how / when to use asPredicate vs. asMatchPredicate. Looking at the following example which produces the same result, is there any difference between the two methods or is it just matter of taste which one to use?

List<String> list = List.of("Java", "Groovy", "Clojure", "JRuby", "JPython");

Predicate<String> p1 = Pattern.compile("^J.*$").asPredicate();
Predicate<String> p2 = Pattern.compile("^J.*$").asMatchPredicate();

List<String> result1 = list.stream().filter(p1).collect(Collectors.toList());
List<String> result2 = list.stream().filter(p2).collect(Collectors.toList());

System.out.println(result1);
System.out.println(result2);

[Java, JRuby, JPython]
[Java, JRuby, JPython]

What ever regex I use (for example ^.*y$ to get all languages which end in y), they seem to produce the same result. The docs mention that asPredicate uses internally matcher.find() and asMatchPredicate uses matcher.matches(). So is there any difference except they call different methods? Or are there differences, for complicated regexes than mine, between matcher.find() and matcher.matches() ?

wannaBeDev
  • 516
  • 3
  • 14
  • 4
    Does this answer your question? [Difference between matches() and find() in Java Regex](https://stackoverflow.com/questions/4450045/difference-between-matches-and-find-in-java-regex) – Federico klez Culloca Aug 12 '22 at 18:50
  • 5
    `matches` tries to match the entire string, so in your case it doesn't make any difference because you have `^` and `$` around your pattern, so you're matching the whole string anyway. – Federico klez Culloca Aug 12 '22 at 18:53
  • @FedericoklezCulloca All right, thank you. I get it. I am dealing with a list of strings and need to match exactly. So for my current use case it doesn't to seem to have a difference, since I am not interested to match for a substring. Thank you. – wannaBeDev Aug 12 '22 at 18:57

0 Answers0