Map遍历的四种方法效率对比_map遍历的几种方式和效率问题
最近在面试的时候笔试碰到一道关于map的题,请手写出map遍历效率最高的方法。
关于map遍历的方式相信大家都知道,但是各个方法的一个效率高低可能有些人平常没有注意,所以在这做了一个简单的测试。
public class MapBianLiXiaoLvBiJiao {
private static Map<Integer,Integer> 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<Integer,Integer> 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<Map.Entry<Integer,Integer>> it=map.entrySet().iterator();
while (it.hasNext()){
Map.Entry<Integer,Integer> 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()遍历的效率是最低
相关文章
- 前端遍历数组时推荐直接for循环一把梭,少用forEach和map的原因
- Map遍历的四种方法效率对比_map遍历的几种方式和效率问题
- 用了那么久的 Java For 循环,你知道哪种方式效率最高吗?
- JS数组中 forEach() 和 map() 的区别
- 掌握 Java 函数式接口高级技巧:Function、Consumer、Supplier 攻略
- Java集合-Map_Java集合体系
- java中遍历map的几种方式_java遍历map效率高
- M3u8视频文件怎么转换成MP4?三种方法随心选!
- M3U8文件怎么转换成MP4?记住这三个转换方法就够了!
- 如何将m3u8视频转成mp4?试试这些软件