Map遍历的四种方法效率对比
最近在面试的时候笔试碰到一道关于map的题,请手写出map遍历效率最高的方法。
关于map遍历的方式相信大家都知道,但是各个方法的一个效率高低可能有些人平常没有注意,所以在这做了一个简单的测试。
publicclassMapBianLiXiaoLvBiJiao{
privatestaticMapInteger,IntegermapnewHashMap();
static{
for(inti0;i10000;i){
intj0;
ji;
map。put(i,j);
}
}
publicstaticvoidmain(String〔〕args){
MapBianLiXiaoLvBiJiaomapBianLiXiaoLvBiJiaonewMapBianLiXiaoLvBiJiao();
mapBianLiXiaoLvBiJiao。foreachMethod();
mapBianLiXiaoLvBiJiao。keySetMethod();
mapBianLiXiaoLvBiJiao。iteratorMethod();
mapBianLiXiaoLvBiJiao。streamForeachMethod();
}
通过foreach遍历entry
publicvoidforeachMethod(){
LongstartTimeSystem。currentTimeMillis();
for(Map。EntryInteger,Integerentry:map。entrySet()){
Integerkeyentry。getKey();
Integervalueentry。getValue();
}
longendTimeSystem。currentTimeMillis();
System。out。println(foreach花费时间为:(endTimestartTime));
}
通过遍历keySet并获取value
publicvoidkeySetMethod(){
LongstartTimeSystem。currentTimeMillis();
for(Integerkey:map。keySet()){
Integervaluemap。get(key);
}
longendTimeSystem。currentTimeMillis();
System。out。println(keySet遍历花费时间为:(endTimestartTime));
}
通过迭代器iterator遍历
publicvoiditeratorMethod(){
LongstartTimeSystem。currentTimeMillis();
IteratorMap。EntryInteger,Integeritmap。entrySet()。iterator();
while(it。hasNext()){
Map。EntryInteger,Integerentryit。next();
Integerkeyentry。getKey();
Integervalueentry。getValue();
}
longendTimeSystem。currentTimeMillis();
System。out。println(iterator遍历花费时间为:(endTimestartTime));
}
通过map。forEach
publicvoidstreamForeachMethod(){
LongstartTimeSystem。currentTimeMillis();
map。forEach((key,value){
Integerkey1key;
Integervalue1value;
});
longendTimeSystem。currentTimeMillis();
System。out。println(转换为流遍历花费时间为:(endTimestartTime));
}
}
执行结果如下:
foreach花费时间为:7
keySet遍历花费时间为:5
iterator遍历花费时间为:1
转换为流遍历花费时间为:122
经过上面的小测试可以看出,通过iterator迭代器对map进行遍历的方式效率是最高的,而map。forEach()遍历的效率是最低