标签:out entry iter new string while java 键值对 shm
Map的遍历可以通过键找值得方式,也可以一个个键值对的遍历
方法一 : iterator+key
Map<String, Object> map = new HashMap<String, Object>();
map.put("name", "Tom");
map.put("age", "5");
//通过key遍历
Set<String> keys = map.keySet();
Iterator<String> iter = keys.iterator();
while (iter.hasNext()) {
String key = iter.next();
Object obj = map.get(key);
System.out.println(key + ":" + obj.toString());
}
方法二: foreach+key
for (String key : map.keySet()) {
System.out.println(key + ":" + map.get(key).toString());
}
方法三:foreach+entry
Set<Map.Entry<String,Object>> entries= map.entrySet();
for (Map.Entry<String,Object> entry :entries){
System.out.println(entry.getKey()+":"+entry.getValue());
}
方法四:iterator+entry
Iterator<Map.Entry<String, Object>> iter = map.entrySet().iterator();
Map.Entry<String,Object> entry;
while (iter.hasNext()) {
entry=iter.next();
System.out.println(entry.getKey()+":"+entry.getValue());
}
在考虑效率方面,for each速度更快一点点,推荐使用for each写法来遍历。
标签:out entry iter new string while java 键值对 shm
原文地址:https://www.cnblogs.com/willsdu/p/13393371.html