How to contain and compare string and array in Java

I’m using array and for loop in condition if to compare ‘searchedValue’ and arrayParameter.

this is my code:

String[] arrayParameter = new String[] {
            "math",
            "physical",
            "literary"
};

boolean found = false;

String searchedValue = "math";
String searchedValue1 = "physical";
String searchedValue2 = "literary";

for(int i=0 ; i< arrayParameter.length; i++) {

    if(arrayParameter[i].equals(searchedValue)) {
        found = true;
        break;
    }
    else if(arrayParameter[i].equals(searchedValue1)) {

        found = true;
        break;
    }
    else if(arrayParameter[i].equals(searchedValue2)) {
        found = true;
        break;
    }
}

HttpEntity<String> entity = new HttpEntity<String>(arrayParameter[i],headers);
String result = restTemplate.postForObject(url, entity, String.class);

logger.debug(result);

When i run my code it cannot compare and return correct result. How to compare/contains ‘searchedValue’ with ‘arrayParameter[i]’ and when string found program will stop and continue to outside of method ?

Answer

  • You are using ‘i’ outside for loop, which is out of its scope.
  • Your write too many if-else statements
boolean found = false;
String foundValue = null;

String searchedValue = "math";
String searchedValue1 = "physical";
String searchedValue2 = "literary";

for(int i=0 ; i< arrayParameter.length; i++) {

if(arrayParameter[i].contains(searchedValue) ||  arrayParameter[i].contains(searchedValue1) || arrayParameter[i].contains(searchedValue2)) {
    found = true;
    foundValue = arrayParameter[i];
    break;
}

}
HttpEntity<String> entity = new HttpEntity<String>(foundValue,headers);
String result = restTemplate.postForObject(url, entity, String.class);

logger.debug(result);

Suggestion:

You can use HashSet instead of String[] array. It will reduce your searching time.

O(1) search:

HashSet<String> setParameter = new HashSet<String>(); 

setParameter.add("math");
setParameter.add("physical");
setParameter.add("literary"); 

if(setParameter.contains(searchedValue) ||  setParameter.contains(searchedValue1) || setParameter.contains(searchedValue2)) {
    found = true;
    foundValue = arrayParameter[i];
    break;
}

Leave a Reply

Your email address will not be published. Required fields are marked *