简体   繁体   中英

Comparing a string with an array list to see if the string contains anything from the list

I have an area where a When the string is submitted, I want to check if that string contains anything from an arrayList. For example, in the arrayList I might have the strings "visit" and "enter" . The user could enter something like "enter village" or "visit cave" . I just want to be able to compare the string to the arrayList to detect for any keywords. If it has keyword from the list, it can act accordingly. The code I have right now looks like this:

if(enterList.contains(text)) //code goes here;

with text being the string the user enters. But the way this works is the opposite of what I want. Its seeing if enterList contains text , not if text contains anything from enterList . Is there any way to see if anything in a string contains anything in a list?

please try with this First split your string by space into array and compare the array with you list like

String[] splited = text.split("\\s+");
if(Collections.disjoint(yourArray, Arrays.asList(splited ))){
//your logic
}

The following code also gets you the tokens that are present and not simply if any of them are present or not.

List<String> listWords; // List of Words against which checking will happen
String sentence; // Concerned String to check

...

Stream.of(sentence.split("[ |.]"))
      .filter(token -> listWords.contains(token))
      .forEach(System.out::println);

The above just prints the token encountered. You can alter the code as follows for adding further logic.

Stream.of(sentence.split("[ |.]"))
      .filter(token -> listWords.contains(token))
      .forEach(f -> {
          // Your logic here
      });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM