2014-10-31 14 views
1

添加我有一個關於下面的代碼有些懷疑名單在Java中獲得價值:如何從自散地圖

public static void main(String[] args) { 
    HashMap<String,String> hMap = new HashMap<String,String>(); 
    System.out.println("Size of HashMap : " + hMap.size()); 
    hMap.put("1", "One"); 
    hMap.put("2", "Two"); 
    hMap.put("3", "Three"); 
    System.out.println("Size of HashMap after addition : " + hMap.size()); 
    // remove one element from HashMap 
    ArrayList<HashMap<String, String>> list; 
    list = new ArrayList<HashMap<String, String>>(); 
    list.add(hMap); 
    System.out.println(""+hMap.get(1)); 
    System.out.println(""+list.size()); 
    //if(list.size()<1) 
    System.out.println(""+list.get(0)); 
} 

輸出

Size of HashMap : 0 
Size of HashMap after addition : 3 
null 
1 
{3=Three, 2=Two, 1=One} 

Myquestion

如何從列表中獲取每個值?

+0

你是什麼讓每一個意思列表中的值? – NewUser 2014-10-31 06:32:51

回答

1

列表中的一個對象,它是一個地圖。如果你希望得到的是一張地圖的價值,只是在它們之間迭代:

for (String value : list.get(0).values()) { 
    System.out.println(value); 
} 

如果您的列表中有多個條目,你可以使用嵌套循環:

for (Map<String,String> map : list) 
    for (String value : map.values()) { 
     System.out.println(value); 
    } 
+0

現在我在該列表中有多個對象如何獲取? – 2014-10-31 06:38:43

+0

@ Test-Developer這就是我在代碼中顯示的內容。遍歷完整列表。至少在提出進一步問題之前閱讀所有答案。對你的答案表示一些尊重。 – 2014-10-31 06:39:12

+0

@ Test-Developer您也遍歷列表 – Eran 2014-10-31 06:44:36

1

如何從列表中獲取每個值?

只是遍歷列表,並獲得每個值

for (HashMap<String, String> currentmap : list) { // foreach loop 
     System.out.println(currentmap);// do something with currentmap 
    for (Map.Entry<String, String> entry : currentmap.entrySet()) { 
     System.out.println(entry.getValue()); //each value of map 
    } 
}