Search code examples
javastringlinked-listequalssearch-keywords

See if a String has keywords provided in LinkedList with equals()


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


Solution

  • After splitting toCheck sentence into words store them in Set since your goal is to check if sentence contains keywords

    • regardless of order,
    • regardless of amount of repetitions (as long as it exists even once).

    Since 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 provides Set#containsAll​(Collection) method and since LinkedList is a Collection we can use it like

    So your code can look like:

    LinkedList<String> keyWords = new LinkedList<String>();
    keyWords.add("amet");
    keyWords.add("eiusmod");
    
    String sentence = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";
    Set<String> wordsInSentence = new HashSet<>(List.of(sentence.trim().split("[ ,.!?]+")));
    
    boolean result = wordsInSentence.containsAll(keyWords);