最近在面试的时候笔试碰到一道关于map的题,请手写出map遍历效率最高的方法。
关于map遍历的方式相信大家都知道,但是各个方法的一个效率高低可能有些人平常没有注意,所以在这做了一个简单的测试。
public class MapBianLiXiaoLvBiJiao {
private static Map
static {
for (int i=0;i<10000;i++){
int j=0;
j+=i;
map.put(i,j);
}
}
public static void main(String[] args) {
MapBianLiXiaoLvBiJiao mapBianLiXiaoLvBiJiao = new MapBianLiXiaoLvBiJiao();
mapBianLiXiaoLvBiJiao.foreachMethod();
mapBianLiXiaoLvBiJiao.keySetMethod();
mapBianLiXiaoLvBiJiao.iteratorMethod();
mapBianLiXiaoLvBiJiao.streamForeachMethod();
}
// 通过foreach遍历entry
public void foreachMethod(){
Long startTime=System.currentTimeMillis();
for (Map.Entry
Integer key= entry.getKey();
Integer value=entry.getValue();
}
long endTime=System.currentTimeMillis();
System.out.println("foreach花费时间为:"+(endTime-startTime));
}
// 通过遍历keySet并获取value
public void keySetMethod(){
Long startTime=System.currentTimeMillis();
for (Integer key:map.keySet()){
Integer value=map.get(key);
}
long endTime=System.currentTimeMillis();
System.out.println("keySet遍历花费时间为:"+(endTime-startTime));
}
// 通过迭代器iterator遍历
public void iteratorMethod(){
Long startTime=System.currentTimeMillis();
Iterator<Map.Entry
while (it.hasNext()){
Map.Entry
Integer key=entry.getKey();
Integer value=entry.getValue();
}
long endTime=System.currentTimeMillis();
System.out.println("iterator遍历花费时间为:"+(endTime-startTime));
}
// 通过map.forEach
public void streamForeachMethod(){
Long startTime=System.currentTimeMillis();
map.forEach((key,value) -> {
Integer key1=key;
Integer value1=value;
});
long endTime=System.currentTimeMillis();
System.out.println("转换为流遍历花费时间为:"+(endTime-startTime));
}
}
执行结果如下:
foreach花费时间为:7
keySet遍历花费时间为:5
iterator遍历花费时间为:1
转换为流遍历花费时间为:122
经过上面的小测试可以看出,通过iterator迭代器对map进行遍历的方式效率是最高的,而map.forEach()遍历的效率是最低