2016-12-29 103 views
0

我用這個代碼添加到hashmap獲取的HashMap的所有子<整數,ArrayList的<String>>

static HashMap<Integer, ArrayList<String>> arrayMap = new HashMap<Integer, ArrayList<String>>(); 

ArrayList<String> list = new ArrayList<String>(); 
list.add("t"); 
list.add("b"); 
arrayMap.put(12, list); 

ArrayList<String> list = new ArrayList<String>(); 
list.add("y"); 
list.add("x"); 
arrayMap.put(18, list); 

這段代碼工作正確

,但我不能得到的arrayMap孩子的foreach

for(arrayMap ....){ 
    return // 12:t,b 18:y,x 
} 

我的嘗試:

for (int a = 0; a < arrayMap.size(); a++) 
     { 
      HashMap<String, Integer> tmpData = (HashMap<String, Integer>) arrayMap.get(a); 
      Set<String> key = tmpData.keySet(); 
      Iterator it = key.iterator(); 
      while (it.hasNext()) { 
       String hmKey = (String) it.next(); 
       Integer hmData = (Integer) tmpData.get(hmKey); 

       System.out.println("Key: " + hmKey + " & Data: " + hmData); 
       it.remove(); // avoids a ConcurrentModificationException 
      } 

     } 
+0

當你說孩子做你是指鍵值對還是值?此外,這些值是列表,所以你的意思是要獲得每個列表的每個元素? –

回答

1

你要遍歷在HashMap中這樣的各條目在嵌套循環:

for(Map.Entry<Integer, ArrayList<String>> entry : arrayMap.entrySet()){ 
    //entry.getKey() will be each key in the HashMap 
    for(String str : entry.getValue()){ 
     // str is one entry of the ArrayList for that Key 
    } 
} 
相關問題