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

57 Views Asked by At

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

3

There are 3 best solutions below

0
On BEST ANSWER

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);
5
On

Why don't you just do this:

public static boolean check(String input, List<String> keywords) {
    for (String keyword : keywords)
        if (!input.contains(keyword))
            return false;

    return true;
}

Which you would call like this in your case:

check(toCheck, keyWords);
6
On

The user, Schred, provided a solution which solves the problem and is perfectly valid. It is worth pointing out this is a perfect opportunity to use Set, specifically HashSet, if you're not bound by LinkedList. This will not work if the words are not case sensative.

Set<String> keywords = new HashSet<>(Arrays.asList("amet", "eiusmod"));

String toCheck = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";

boolean contains = Stream.of(toCheck.split(" ")).allMatch(keywords::contains);