2016-12-29 47 views
-4

我有以下代碼:如何根據條件找到未找到映射中的鍵的邏輯?

for(String s1 : source){ 
    for(String s2 : target){ 
     if(s1.length() > 4 && s2.length() > 4){ 
      String sKey = s1.substring(1,5); 
      String tKey = s2.substring(1,5); 
      if(sKey.equals(tKey)){ 
       //Do your logic... 
      }else if(!sKey.equals(tKey) && sKey not availlable in the target list){ 
       //print the value that sKey not availlable in target 
      } 
     } 
    } 
} 

我需要打印的值,如果鍵沒有整個清單的完整穿越找到。

請幫忙!!

+2

你能解釋你到底想要達到什麼嗎? – Mureinik

+0

如果密鑰在第二個列表中不可用,那麼我必須打印此密鑰在目標/第二個列表中不可用,反之亦然。 – vermaraj

+0

這是一個列表還是地圖,還是你有每一個?您的標題說'地圖',但您的for循環不會將'source'和'target'視爲地圖,並且您的文本顯示「遍歷列表」。 「目標」是「列表」嗎? –

回答

1

顯而易見的解決方案是使用contains方法添加一個條件,並檢查條件在末端。

for(String s1 : source){ 
    boolean found = false; 
    for(String s2 : target){ 
     if(s1.length() > 4 && s2.length() > 4){ 
      String sKey = s1.substring(1,5); 
      String tKey = s2.substring(1,5); 
      if(sKey.equals(tKey)){ 
       found=true; 
       break; 
      } 
     } 
    } 
    if(found){ 
     //found logic 
    } else{ 
     //not found logic 
    } 
} 

這個問題,你每次都在做一個新的子字符串。相反,我會建議創建一個鍵列表。

List<String> targetKeys = target.stream().filter(
      s->s.length()>4 
    ).map(
      s->s.substring(1,5) 
    ).collect(Collectors.toList()); 

List<String> sourceKeys = source.stream().filter(
      s->s.length()>4 
    ).map(
      s->s.substring(1,5) 
    ).collect(Collectors.toList()); 

然後你可以做類似的事情。

sourceKeys.removeAll(targetKeys); 

如果你將只剩下不存在的鑰匙。

1

List

if (!targetList.contains(sKey)) { 
// System.out.println("this will print only if the sKey not present in targetList"); 
} 
+1

如果您注意到密鑰不一定是列表中的完整字符串。 – matt

0

如果我得到正確的你正在嘗試做的,這應該這樣做:

   } else if (!target.stream().map(s -> s.substring(1, 5)).anyMatch(s -> s.equals(tKey))) { 

,因爲你是在第一if聲明else部分不需要條件的!sKey.equals(tKey)部分,所以我們已經知道密鑰是不相等的。

由於我們現在在代碼中的三個位置執行substring(1, 5),因此可能需要將其分解爲單獨的方法。

這是題外話,我建議把這個行:

 String sKey = s1.substring(1, 5); 

那還不如兩個for (String線之間去。不需要從s1中取出每s2一次的子字符串。