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");
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");
}