测试说明:拿100W条记录塞进了HashMap中进行遍历,遍历时间均为毫秒
测试结果:
start put elements!
start test...
map size:1000000
method1 spend:94
method2 spend:78
method3 spend:94
method4 spend:47
结果表明,第二种方式要有于1和3,第四种无可比性,因为它只是遍历出了Value,如果不需要key可以使用第四种方式。
附带测试程序:
package map;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* HashMap遍历测试程序
*
* @author 开源吧,http://www.kaiyuanba.cn
* @since Nov 13, 2011
*/
public class HashMapTraverser {
public static void main(String[] args) {
Map<String, String> _map = new HashMap<String, String>();
System.out.println("start put elements!");
for (int i = 0; i < 1000000; i++) {
_map.put("key" + i, "value" + i);
}
System.out.println("start test...");
long step1 = System.currentTimeMillis();
traverserOne(_map);
long step2 = System.currentTimeMillis();
traverserTwo(_map);
long step3 = System.currentTimeMillis();
traverserThree(_map);
long step4 = System.currentTimeMillis();
traverserFour(_map);
long step5 = System.currentTimeMillis();
System.out.println("map size:" + _map.size());
System.out.println("method1 spend:" + (step2 - step1));
System.out.println("method2 spend:" + (step3 - step2));
System.out.println("method3 spend:" + (step4 - step3));
System.out.println("method4 spend:" + (step5 - step4));
}
/**
* 第一种遍历方法
*
* @param map
*/
public static void traverserOne(Map<String, String> map) {
Set<String> _set = map.keySet();
for (String _s : _set) {
// System.out.println(s + "," + map.get(s));
String _key = _s;
String _value = map.get(_s);
}
}
/**
* 第二种遍历方法
*
* @param map
*/
public static void traverserTwo(Map<String, String> map) {
Set<Map.Entry<String, String>> _entryseSet = map.entrySet();
for (Map.Entry<String, String> _entry : _entryseSet) {
String _key = _entry.getKey();
String _value = _entry.getValue();
}
}
/**
* 第三种遍历方法
*
* @param map
*/
public static void traverserThree(Map<String, String> map) {
Iterator<String> it = map.keySet().iterator();
while (it.hasNext()) {
String _key = it.next();
String _value = map.get(_key);
}
}
/**
* 第四种遍历方法
*
* @param map
*/
public static void traverserFour(Map<String, String> map) {
Iterator<String> it = map.values().iterator();
while (it.hasNext()) {
String _val = (String) it.next();
}
}
}