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
toChecksentence into words store them inSetsince your goal is to check if sentence contains keywordsSince Sets are optimized towards contains method (for HashSet
containsis close to O(1) time complexity) it looks like valid choice for this scenario.Also
SetprovidesSet#containsAll(Collection)method and sinceLinkedListis aCollectionwe can use it likeSo your code can look like: