簡體   English   中英

如何在 Java 中包含和比較字符串和數組

[英]How to contain and compare string and array in Java

如果比較'searchedValue'和arrayParameter,我正在使用數組和for循環。

這是我的代碼:

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

當我運行我的代碼時,它無法比較並返回正確的結果。 如何比較/包含“searchedValue”與“arrayParameter[i]”以及何時找到字符串程序將停止並繼續到方法之外?

  • 您在 for 循環之外使用“i”,它超出了它的 scope。
  • 你寫了太多的 if-else 語句
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:

您可以使用 HashSet 代替 String[] 數組。 它將減少您的搜索時間。

O(1) 搜索:


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

我認為您可以輕松地使用Arrays.asList(arrayParameter).contains(searchedValue)來創建您的意圖方法。 有了這個,你可以消除循環。 請注意,如果您使用以下方法,如果沒有匹配項,則不會調用您的 API。 但是在上面的示例 API 調用即使沒有匹配項也會進行, null用於foundValue。

if (Arrays.asList(arrayParameter).contains(searchedValue)){
    callApi(searchedValue)
}
if (Arrays.asList(arrayParameter).contains(searchedValue1)){
    callApi(searchedValue1)
}
if (Arrays.asList(arrayParameter).contains(searchedValue2)){
    callApi(searchedValue2)
}

private void callApi(String foundValue){
   
    HttpEntity<String> entity = new HttpEntity<String>(foundValue,headers);
    String result = restTemplate.postForObject(url, entity, String.class);
    logger.debug(result);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM