Map遍历的四种方法效率对比

最近在面试的时候笔试碰到一道关于map的题,请手写出map遍历效率最高的方法。

关于map遍历的方式相信大家都知道,但是各个方法的一个效率高低可能有些人平常没有注意,所以在这做了一个简单的测试。

public class MapBianLiXiaoLvBiJiao {

private static Map map=new HashMap<>();

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 entry:map.entrySet()){

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> it=map.entrySet().iterator();

while (it.hasNext()){

Map.Entry entry=it.next();

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()遍历的效率是最低

展开阅读全文

页面更新:2024-03-03

标签:遍历   效率   方法   笔试   平常   最低   简单   方式   测试

1 2 3 4 5

上滑加载更多 ↓
推荐阅读:
友情链接:
更多:

本站资料均由网友自行发布提供,仅用于学习交流。如有版权问题,请与我联系,QQ:4156828  

© CopyRight 2008-2024 All Rights Reserved. Powered By bs178.com 闽ICP备11008920号-3
闽公网安备35020302034844号

Top