假设创建了如下的map:
Map<String,String> map = new HashMap<String,String>();
for(int i = 1001;i<149511;i++){
map.put(i+"",i+"");
}
遍历map有五种遍历方式,如下所示:
2.1 通过增强型for遍历keySet
long start1 = System.currentTimeMillis();
String value2 = null;
for(String key : map.keySet()){
value2 = map.get(key);
//System.out.print(value2+" ");
}
long end1 = System.currentTimeMillis();
System.out.println("\n耗时:"+(end1 - start1));
2.2通过迭代器遍历ketSet
l
ong start2 = System.currentTimeMillis();
Iterator<String> keySetIt = map.keySet().iterator();
String value3 = null;
String key = null;
while(keySetIt.hasNext()){
key = keySetIt.next();
value3 = map.get(key);
//System.out.print(value3+" ");
}
long end2 = System.currentTimeMillis();
System.out.println("\n耗时:"+(end2 - start2));
2.3通过values来遍历map的value值
long start3 = System.currentTimeMillis();
Collection<String> c = map.values();
Iterator<String> it = c.iterator();
String value4 = null;
for(;it.hasNext();){
value4 = it.next();
// System.out.print(value4+" ");
}
long end3 = System.currentTimeMillis();
System.out.println("\n耗时:"+(end3 - start3));
2.4通过增强型for的entrySet遍历key、value
String key2 = null;
String value5 = null;
long start4 = System.currentTimeMillis();
for(Entry<String,String> entry:map.entrySet()){
key2 = entry.getKey();
value5 = entry.getValue();
// System.out.print(key2+" "+value5+" ");
};
long end4 = System.currentTimeMillis();
System.out.println("\n耗时:"+(end4 - start4));
2.5通过entrySet和迭代器遍历key、value
String key3 = null;
String value6 = null;
long start5 = System.currentTimeMillis();
Iterator<Entry<String,String>> mapEntryIt = map.entrySet().iterator();
Entry<String,String> entry = null;
while(mapEntryIt.hasNext()){
entry = mapEntryIt.next();
key3 = entry.getKey();
value6 = entry.getValue();
// System.out.print(key3+" "+value6+" ");
}
long end5 = System.currentTimeMillis();
System.out.println("\n耗时:"+(end5 - start5));
/**output:
耗时:28
耗时:17
耗时:13
耗时:18
耗时:11
*/
从结果我们可以看出:如果是遍历key和value,那么使用entrySet迭代器的方式遍历map效率最佳;如果只遍历value,那么可以既可以使用entrySet迭代器的方式遍历map也可以使用values遍历map。