2016-05-17 68 views
-3

我已經成功實施的HashMap爲我的項目,現在我stucked這裏..如何在HashMap中成功比較兩個字符串?

這是我的HashMap ......它會提取SQL數據,並且將投入HashMap的...

private Map<String, String> list = new HashMap<String, String>(); 
sql.... extract data .... 
while (...) { 
    list.put(string1, string2); 
} 

所以..現在我有兩個字符串...

a = mike; 
b = james; 

因爲它是同步的HashMap ..我想找出我該怎麼做..

if (list.containsKey=a+b)? or if (list.containsValue=a+b)? 
if (list.containsKey(a) && list.containsValue(b)) { 
    do.... 
} else { 
    do nth... 
} 

我試圖比較兩個值,我需要兩個匹配和相互鏈接..我試着玩它,但它看起來像當它匹配一.. ..它做的事情..它只是需要匹配一個...

但我想要在列表中找到邁克和詹姆斯,然後運行....東西..我打印出列表的結果,它顯示邁克=詹姆斯。

如何這樣做是爲了看看邁克·詹姆斯= ...然後..存在其他..在列表不存在..

+0

「成功實施的HashMap」請​​解釋 – piyushj

+0

它如預期運行。只是,我不知道如何比較或成功比較鍵/值同步。像mike = james,那麼在繼續操作之前如何確保兩個字符串都是正確的呢? – Nicky

回答

2

一個HashMap(或任何其他Map)不僅僅是2個列表或「對」的列表,它是從1個元素(密鑰)到另一個()的映射。

您選擇的地圖名稱(「列表」)表明您正在考慮它,就好像它只是一個列表,而這會導致您走錯了路。

你想看到的字符串一個( 「邁克」)是否映射到b( 「詹姆斯」)。

要求在地圖上查找a並對b測試結果。

你想要的東西像

String m = map.get(a) 
if(m != null && m.equals(b)) { 
    // ... 
} else { 
    // ... 
} 
+0

謝謝,簡單又容易 – Nicky

2

真的很難理解你所追求的。如果你正在尋找一個元組,像下面將工作:

public static void main(String[] args) { 
    Map<String, String> map = new HashMap<>(); 

    map.put("mike", "james"); 

    printTupleIfFound(map, "mike", "james"); 
} 

private static void printTupleIfFound(Map<String, String> map, String fst, String snd) { 
    for (Entry<String, String> entry : map.entrySet()) { 
     if (entry.getKey().equals(fst) && entry.getValue().equals(snd)) { 
      System.out.println(fst + "," + snd + " is in the map"); 
     } else { 
      System.out.println(fst + "," + snd + " is NOT in the map"); 
     } 
    } 

}