可能重複:
How do I iterate over each Entry in a Map?
How can I iterate over a map of <String, POJO>?遍歷HashMap中
我已經寫了下面的一段代碼和我被困在遍歷HashMap中。
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
class demo
{
public static void main(String v[]) {
ArrayList<String> contactIds = new ArrayList<String>();
contactIds.add("2");
contactIds.add("3");
HashMap names = new HashMap();
names = getNames(contactIds);
// I want to get the total size of the hashmap - names
// for ex now there are 6 elements inside hashmap.
// How can I get that count?
}
private static HashMap getNames(ArrayList contactIds) {
HashMap names = new HashMap();
String params = null;
List<String> list = new ArrayList<String>();
for(int i=0; i<contactIds.size();i++) {
params = contactIds.get(i).toString();
list.add(0,"aer-1");
list.add(1,"aer-2");
list.add(2,"aer-3");
names.put(params,list) ;
}
return names;
}
}
在這段代碼中,地圖中有六個元素,現在在主要方法中,我如何迭代地圖並獲得總數?
謝謝。
但是我怎樣才能得到hashmap中元素的總數。 例如,爲鍵1和鍵2添加了3個元素。 現在我希望總大小爲6。可能嗎 ? – nithin