2012-03-03 44 views
0

我在這裏有這個方法從JList獲取對象。該對象將是一個匹配hashmap中某些值的字符串。例如,有多個值。根據值顯示hashmap的入口集

Course1 - John 
Course2 - John 
Course3 - Mary 
Course4 - Mary 

在那裏循環任何方式通過一個HashMap,尋找一定的價值,然後將兩個鍵&值成,然後可以添加到列表模式的字符串?

回答

1

如果您只是在搜索值,請使用hashmap的keySet()方法獲取密鑰,然後遍歷它們以獲取相應的值。

for(String key : hashMap.keySet()) 
    { 
    String value = hashMap.get(key); 

    if(searchString.equals(value)) 
     { 
      String keyAndValue = key + value; // this is what you want 
     }  
    } 

如果您正在搜索鍵和值,使用HashMap中的的entrySet()方法,通過它們來獲取條目,然後循環來尋找匹配。

for(Map.Entry<String, String> entry : hashMap.entrySet()) 
    { 
    String key = entry.getKey(); 
    String value = entry.getValue(); 

    if(searchString.equals(key) || searchString.equals(value)) 
     { 
      String keyAndValue = key + value; // this is what you want 
     }  
    } 
+0

他想通過搜索** *值***。您剛剛將'get()'重新實現爲線性(O(n))搜索。 – 2012-03-03 06:59:19

+0

好的,我會做出改變。我假設他想要根據關鍵和價值進行搜索。 – CodeBlue 2012-03-03 07:03:02

+1

其實,CodeBlue提供了一個完美的工作代碼。你是一個拯救生命的人! – cataschok 2012-03-03 07:04:56

1

使用其在地圖上進行迭代,並返回匹配列表的搜索方法:

public static ArrayList <String> searchMap (HashMap map, String value) 
{ 
    ArrayList <String> matchesFound = new ArrayList <String>(); 
    Iterator it = map.entrySet().iterator(); 
    while (it.hasNext()) 
    { 
     Map.Entry entry = (Map.Entry) it.next(); 
     if (entry.getValue() == value) 
      matchesFound.add(entry.getKey() + " : " + entry.getValue()); 
    } 
    return matchesFound; 
} 

樣品使用與填充HashMap的數據:

public static void main (String [] args) 
{ 
    HashMap < String, String > map = new HashMap < String, String >(); 
    map.put("Course1", "John"); 
    map.put("Course2", "John"); 
    map.put("Course3", "Mary"); 
    map.put("Course4", "Mary"); 
    System.out.println(searchMap(map, "Mary")); 
} 
+0

他想通過***值***進行搜索。儘管您的解決方案可以很容易地修復,但您已經將'get()'重新實現爲線性(O(n))搜索。 – 2012-03-03 07:03:37

+0

@JimGarrison請檢閱我的帖子。 – Juvanis 2012-03-03 07:09:31

+0

我需要顯示輸入值的所有匹配鍵/值條目。所以codeblue提供的代碼完美工作。不過,我會記住你的方法,以防將來出現類似情況。 – cataschok 2012-03-03 07:16:50