fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6. import java.util.regex.*;
  7. import java.util.stream.*;
  8.  
  9. /* Name of the class has to be "Main" only if the class is public. */
  10. class Ideone
  11. {
  12. public static void main (String[] args) throws java.lang.Exception
  13. {
  14. String testString = "a b c d ab ac ad da ca ba d e b z s aa";
  15. long startTime;
  16.  
  17.  
  18. String[] keywords = {"a", "ab", "ad", "c", "d", "j", "k", "sz", "hk", "ok"};
  19. List<Pattern> patterns = Arrays.asList(keywords).stream().map(keyword -> Pattern.compile("\\b"+keyword+"\\b")).collect(Collectors.toList());
  20. startTime = System.nanoTime();
  21. for (Pattern p : patterns) {
  22. Matcher m = p.matcher(testString);
  23. while (m.find()) { System.out.println(m.group()); }
  24. }
  25. System.out.printf("Took %s ms%n", (System.nanoTime() - startTime) / 1000);
  26.  
  27. Pattern multiPattern = Pattern.compile("\\b(a[bd]?|c|d|j|[oh]?k|sz)\\b");
  28. startTime = System.nanoTime();
  29. Matcher m = multiPattern.matcher(testString);
  30. while (m.find()) { System.out.println(m.group()); }
  31. System.out.printf("Took %s ms%n", (System.nanoTime() - startTime) / 1000);
  32. }
  33. }
Success #stdin #stdout 0.09s 711680KB
stdin
Standard input is empty
stdout
a
ab
ad
c
d
d
Took 783 ms
a
c
d
ab
ad
d
Took 193 ms