Reputation: 7
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?
Upvotes: 1
Views: 160
Reputation: 4131
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
});
Upvotes: 0
Reputation: 1434
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
}
Upvotes: 2