map遍历

Posted renjianjun

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了map遍历相关的知识,希望对你有一定的参考价值。

向map中添加数据 150万
Map<String,String> m = new HashMap<>(); for (int i = 0; i < 1500000; i++) { m.put("a" + i,"1"); } long start2 = System.currentTimeMillis(); Set<Map.Entry<String, String>> entries1 = m.entrySet(); Iterator<Map.Entry<String, String>> iterator = entries1.iterator(); while (iterator.hasNext()){ Map.Entry<String, String> next = iterator.next(); System.out.println(next.getKey() + next.getValue()); } long iteratorTime = System.currentTimeMillis() - start2; long start = System.currentTimeMillis();for (Map.Entry<String, String> entry : m.entrySet()) { System.out.println(entry.getKey() + " " + entry.getValue()); } long entrySetTime = System.currentTimeMillis() - start; long start1 = System.currentTimeMillis(); for (String s : m.keySet()) { System.out.println(s + " " + m.get(s)); } long keySetTime = System.currentTimeMillis() - start1; System.out.println("iteratorTime" + iteratorTime); System.out.println("entrySetTime" + entrySetTime); System.out.println("keySetTime" + keySetTime);


第一次运行的结果:

  iteratorTime5556
  entrySetTime5620
  keySetTime5779

 第二次运行结果

  iteratorTime5194
  entrySetTime5267
  keySetTime5296

再运行几次 

iteratorTime5465
entrySetTime5594
keySetTime5703

map数据是10万左右的时候运行多次,结果就不一样了,三个都有最快的时候,不知道为什么,但是从数据最多的情况来分析,还是iterator方式遍历的速度是最快的。

所以,我们使用中为了速度,我们使用iterator

写代码简单

keySet和entrySet 省事儿

 

 

以上是关于map遍历的主要内容,如果未能解决你的问题,请参考以下文章

Groovymap 集合 ( map 集合遍历 | 使用 map 集合的 find 方法遍历 map 集合 | 代码示例 )

CSP核心代码片段记录

RecyclerView holder中的Android Google Maps动态片段

将多个输出中的hls属性设置为单独的片段代码

velocity两种map遍历方法

java Map 怎么遍历