Given this situation, i want to see if the string contains ALL of the given keywords, atleast once/word. My for loop does not seem to do it, so i'm interested if there is another way to try to solve the problem.
LinkedList<String> keyWords = new LinkedList<String>();
keyWords.add("amet");
keyWords.add("eiusmod");
String toCheck = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";
String[] toCheckWords = toCheck.split(" ");
for (int i=0; i<toCheckWords.length(); i++) {
if (keyWords.get(i).equals(toCheckWords[i])
return true;
}
return false;
Expected to return true
After splitting
toCheck
sentence into words store them inSet
since your goal is to check if sentence contains keywordsSince Sets are optimized towards contains method (for HashSet
contains
is close to O(1) time complexity) it looks like valid choice for this scenario.Also
Set
providesSet#containsAll(Collection)
method and sinceLinkedList
is aCollection
we can use it likeSo your code can look like: