fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4.  
  5. class TokenMatcher {
  6.  
  7. public TokenMatcher(List<String> tokenList) {
  8. this.tokenList = tokenList;
  9. }
  10.  
  11. List<String> tokenList;
  12.  
  13. List<String> findSentencesWith(String... tokens) {
  14. List<String> results = new ArrayList<String>();
  15.  
  16. // start by assuming they're all good...
  17. results.addAll(tokenList);
  18.  
  19. for (String str : tokenList) {
  20. for(String t : tokens) {
  21. // ... and remove it from the result set if we fail to find a token
  22. if (!str.contains(t)) {
  23. results.remove(str);
  24.  
  25. // no point in continuing for this token
  26. break;
  27. }
  28. }
  29. }
  30.  
  31. return results;
  32. }
  33.  
  34. public static void main (String[] args) throws java.lang.Exception
  35. {
  36. List<String> tokenList = new ArrayList<String>();
  37. tokenList.add("How now a1 cow.");
  38. tokenList.add("The b1 has oddly-shaped a2.");
  39. tokenList.add("I like a2! b2, b2, b2!");
  40.  
  41. TokenMatcher matcher = new TokenMatcher(tokenList);
  42.  
  43. List<String> results = matcher.findSentencesWith("a1"); // Returns 1 String ("How now a1 cow")
  44.  
  45. for (String r : results) {
  46. System.out.println("1 - result: " + r);
  47. }
  48.  
  49. List<String> results2 = matcher.findSentencesWith("b1"); // Returns 1 String ("The b1 has oddly-shaped a2.")
  50.  
  51. for (String r : results2) {
  52. System.out.println("2 - result: " + r);
  53. }
  54.  
  55. List<String> results3 = matcher.findSentencesWith("a2"); // Returns the 2 Strings with a2 in them since "a2" is all we care about...
  56.  
  57. for (String r : results3) {
  58. System.out.println("3 - result: " + r);
  59. }
  60.  
  61. List<String> results4 = matcher.findSentencesWith("a2", "b2"); // Returns 1 String ("I like a2! b2, b2, b2!.") because we care about BOTH tokens
  62.  
  63. for (String r : results4) {
  64. System.out.println("4 - result: " + r);
  65. }
  66. }
  67. }
  68.  
  69.  
Success #stdin #stdout 0.07s 380160KB
stdin
Standard input is empty
stdout
1 - result: How now a1 cow.
2 - result: The b1 has oddly-shaped a2.
3 - result: The b1 has oddly-shaped a2.
3 - result: I like a2! b2, b2, b2!
4 - result: I like a2! b2, b2, b2!