Map key重复则会出现最后一次put的value //HashMap TreeMap
遍历Map
Map<Object, Object> map = new HashMap<Object, Object>();
- 老版本遍历,泛型1.5以上 ,可以进行entry移除的操作
//iterator.remove();
Iterator<Map.Entry<Object, Object>> it = map.entrySet().iterator();
while(it.hasNext()){
Entry<Object, Object> entry = it.next();
System.out.println("key:"+entry.getKey()+":"+"value"+entry.getValue());
}
- 1.5以上
for(Object key:map.keySet()){
System.out.println("key:"+key+":"+"value"+map.get(key));
}
for(Map.Entry<Object, Object> entry:map.entrySet()){
System.out.println("key:"+entry.getKey()+":"+"value"+entry.getValue());
}
- 只进行key或value遍历,视具体情况
Collection<Object> values = map.values();
Set<Object> keySet = map.keySet();
总结:
如果只需要遍历key或value,那采用4方法速度是最快的除去该种情况,推荐使用3方法,速率相对来说最好
1方法肯定能用
2方法据键取value遍历速率不理想