遍历HashMap
作者:admin 日期:2007-09-14
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();
}
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();
}
评论: 0 | 引用: 0 | 查看次数: 1765
发表评论
你没有权限发表留言!