HashMap的keySet遍历和entrySet遍历时间效率比较

时间:2020-12-05 17:41:40
import java.util.Calendar;
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

public class HashMapTest {
public static void main(String[] args) {

Map<Integer, String> map = new HashMap<Integer, String>();
for (int i = 0; i <= 5000000; i++) {
map.put(i, "a" + i);
}

//遍历方法1
Set<Integer>set = map.keySet();
Iterator iterator1 = set.iterator();
long startTime1 = Calendar.getInstance().getTimeInMillis(); //开始时间
while (iterator1.hasNext()) {
Object key = iterator1.next();
Object value = map.get(key);
}
long endTime1 = Calendar.getInstance().getTimeInMillis();
System.out.println("costTime1 = " + (endTime1 - startTime1)); //结束时间

//遍历方法2
Iterator iterator2 = map.entrySet().iterator();
long startTime2 = Calendar.getInstance().getTimeInMillis(); //开始时间
while (iterator2.hasNext()) {
Map.Entry<Integer, String> entry = (Map.Entry<Integer, String>) iterator2.next();
Object key = entry.getKey();
Object val = entry.getValue();
}
long endTime2 = Calendar.getInstance().getTimeInMillis(); //结束时间
System.out.println("costTime2 = " + (endTime2 - startTime2));
}
}




输出结果:
costTime1 = 138costTime2 = 77