Example 1: 通过迭代key得到value中的值
try {
HashMap hm = new HashMap();
hm.put("1", "yi");
hm.put("2", "er");
hm.put("3", "san");
hm.put("4", "si");
hm.put("5", "wu");
Iterator it=hm.keySet().iterator();
while(it.hasNext()){
String key=(String)it.next();
System.out.println(hm.get(key));
}
} catch (Exception e) {
e.printStackTrace();
}
Example 2:直接迭代value中的值
try {
HashMap hm = new HashMap();
hm.put("1", "yi");
hm.put("2", "er");
hm.put("3", "san");
hm.put("4", "si");
hm.put("5", "wu");
Iterator it=hm.values().iterator();
while(it.hasNext()){
System.out.println(it.next());
}
} catch (Exception e) {
e.printStackTrace();
}
Example 3: 同时获得key和value
try {
HashMap hm = new HashMap();
hm.put("1", "yi");
hm.put("2", "er");
hm.put("3", "san");
hm.put("4", "si");
hm.put("5", "wu");
Iterator it=hm.entrySet().iterator();
while(it.hasNext()){
Map.Entry map=(Map.Entry)it.next();
System.out.println(map.getKey()+" - "+map.getValue());
}
} catch (Exception e) {
e.printStackTrace();
}