Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I check if the list contains the value listed in array list?

I have an array of strings that contains URL
String[] stringUrl = ["abc.com", "xyz.com", "est.com"]

The requirement is to find the match. I iterate over the array as soon as I find the match I break from the loop
I have the below code:

public void determineMatchedString(String envUrl){

for (int i = 0; i < stringUrl.size(); i++) 
        {
            if(stringUrl(i).equalsIgnoreCase(envUrl)) {
                logger.info("matched"));
                break;
            }else {
                logger.info("we are picking the default value");
            }
        }
}

In the envUrl when I pass "xyz.com" as a parameter it prints the else part logger.info("we are picking the default value");

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

However, the value "xyz.com" is present in an array.

Expected Output: logger.info("matched"));
Actual Output: logger.info("we are picking the default value");

>Solution :

You print out a logging row in every iteration of the list. Instead, you should print out ""we are picking the default value" only after the loop, if the match is not found:

boolean found = false;
for (int i = 0; i < stringUrl.size(); i++) {
    if (stringUrl[i].equalsIgnoreCase(envUrl)) {
        logger.info("matched"));
        found = true;
        break;
    }
}
if (!found) {    
    logger.info("we are picking the default value");
}

Side note:
Using streams would make this code a bit neater:

if (Arrays.stream(stringUrl).anyMatch(s -> s.equalsIgnoreCase(envUrl))) {
    logger.info("matched"));
} else {
    logger.info("we are picking the default value");
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading