1

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?

asked May 3, 2016 at 21:27
4
  • What do you mean by text contains anything from enterList? Commented May 3, 2016 at 21:30
  • 3
    Try a for loop: for (String word : enterList) if (text.contains(word)) return true; return false; Commented May 3, 2016 at 21:33
  • @ShreyosAdikari what I mean is I want to see if anything in the arrayList is in the string called text. So even if the string is "visit village" and the arrayList only contains a string equal to "visit", it'll detect that text contains something from the list. Commented May 3, 2016 at 21:35
  • @TechBandit Got it. Then you have to use for loop as Andreas said. Commented May 3, 2016 at 21:36

2 Answers 2

2

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
}
answered May 3, 2016 at 21:37
0

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
 });
answered May 4, 2016 at 4:55

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.