Home > Enterprise >  Minimizing multiple contain statements
Minimizing multiple contain statements

Time:04-13

After reading some other similar questions, I found that you cannot use a switch statement to check for more than one .contains tasks that result in different outcomes. I don't want to keep repeating if(string.contains("") for a single string. How else can I minimize the amount of .contain statements or is there actually a way I can implement a switch?

CodePudding user response:

Using for loop to iterate through words to archive multiple .contains check.

First, create a class that validates your string input.

public class StringValidator {

    String[] words = new String[]{"apple", "banana", "orange"};

    public boolean isMatchAll(String input) {
        for (String word : words) {
            if (!input.contains(word)) {
                return false;
            }
        }
        return true;
    }
}

Then call StringValidator.isMatchAll to check whether your string input is match all words

StringValidator stringValidator = new StringValidator();
String input = "I like apple, banana and orange.";
boolean isMatch = stringValidator.isMatchAll(input); //  true

CodePudding user response:

You could use a switch statement, but it would need to be paired with a loop that cycles multiple times for each word that needs to be matched.

Consider the following code that does the same thing, but with only a single contains statement written in code. The trick is that we simply create a list of words that need to be matched, and we pass your string and those words into a helper method which returns true if all the words matched:

//Sample list of words to match
String[] words = new String[]{"some", "example", "words"};
//Sample text to check
String yourText = "This is an example of some words to check for";

//Now we call our helper method containsList(yourText, words)
if (containsList(yourText, words)){
    System.out.println("All words found");
}   
else{
    System.out.println("Not all words found");
}

And the following helper method is all the code we need, it simply uses a for loop to check each word and return true of false:

public static boolean containsList(String yourText, String[] listOfWords){
    for (String word : listOfWords)
    {
        if(yourText.contains(word) == false)
        //Break as soon as a match is not found
        return false;
    }
    //Return true if all words in the words list were found
    return true;
}

The result from our sample text is true and will print out "All words found".

Note that this may not a very efficient solution for large data sets, but you have not indicated in your question that you are working with large data, and this will work just fine in most cases.

  • Related