How to check if a string has a substring from a list?

I am looking for a better way to check if a string contains a substring from a list of keywords.

For example, I create a list like this:

List<String> keywords = new ArrayList<>();
keywords.add("mary");
keywords.add("lamb");

String s1 = "mary is a good girl";
String s2 = "she likes travelling";

Line s1 has a "mary" of keywords, but line s2 does not. So, I would like to define a method:

boolean containsAKeyword(String str, List<String> keywords)

Where it containsAKeyword(s1, keywords)returns true, but containsAKeyword(s2, keywords)returns false. I can return true even if there is one subscript match.

I know that I can just iterate over the list of keywords and call str.contains () for each item in the list, but I was wondering if there is a better way to iterate over the entire list (avoid the complexity of O (n)), or if Java provides for of this inline methods.

+4
7

. , for:

for(String listItem : myArrayList){
   if(myString.contains(listItem)){
      // do something.
   }
}

, - . , , , ?

2

, , - . , , , . return false statement , , , , . :

public boolean containsAKeyword(String myString, List<String> keywords){
   for(String keyword : keywords){
      if(myString.contains(keyword)){
         return true;
      }
   }
   return false; // Never found match.
}
+6

true, . false .

public boolean containsAKeyword(String str, List<String> keywords){
    for(String k : keywords){
        if(str.contains(k))
            return true;
    }

    return false;
}
+2

JDK8 :

public static boolean hasKey(String key) {
   return keywords.stream().filter(k -> key.contains(k)).collect(Collectors.toList()).size() > 0;
}

hasKey(s1); // prints TRUE
hasKey(s2); // prints FALSE
+2

List<String> keywords = new ArrayList<>();
keywords.add("mary");
keywords.add("lamb");

String s1 = "mary is a good girl";
String s2 = "she likes travelling";
// The function
boolean check(String str, List<String> keywords)
  Iterator<String> it = keywords.iterator();
  while(it.hasNext()){
    if(str.contains(it.next()))
       return true;
  }
  return false;
}
+1

, , String:

String s1 = "mary is a good girl";
if(s1.contains("mary")
{
   //Success
}

, , , [ ASCII] [ hashvalue] (, Array) , , , hashvalue , , .

, !

0

You can add all words to keywords in hashmap. You can then use str.contains for line 1 and line 2 to check if keywords are available.

0
source

Depending on the size of the list, I would suggest using the matches () method for String. String.matches takes a regex argument, which with smaller lists you could build a regular expression and evaluate it:

String Str = new String("This is a test string");
System.out.println(Str.matches("(.*)test(.*)"));

This should print "true".

Or you can use java.util.regex.Pattern.

0
source

All Articles