一、目的

在我们编写Java代码的过程中,Map是我们常用的存储数据的类型,因为他的查询效率非常的高。如果想要遍历Map的话,是使用keySet()方法,是entrySet()方法,是迭代器,是forEach呢?

下面通过实验说明:建议使用entrySet(),最好是forEach.

二、测试过程

下面是测试Map遍历的代码:


/** * Licensed to the Apache Software Foundation (ASF) under one or more* contributor license agreements.  See the NOTICE file distributed with* this work for additional information regarding copyright ownership.* The ASF licenses this file to You under the Apache License, Version 2.0* (the "License"); you may not use this file except in compliance with* the License.  You may obtain a copy of the License at**     http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.**/
package com.tompai.common.utils;import java.time.Duration;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;import org.apache.commons.lang3.RandomStringUtils;/*** @desc: snow* @name: MapTest.java* @author: tompai liinux@qq.com* @createTime: 2019年11月24日 下午10:13:40* @history:* @version: v1.0*/public class MapTest {/*** @author: tompai* @createTime: 2019年11月24日 下午10:13:40* @history:* @param args void*/public static void main(String[] args) {int initialCapacity=16;int aHundredMillion = 10000000;Map<String, String> hm = new HashMap<String, String>(initialCapacity);for(int i=0;i<aHundredMillion;i++) {String sts=RandomStringUtils.random(6, true, true);hm.put(String.valueOf(i), sts);}// 1. keySetInstant start=Instant.now();for (String key : hm.keySet()) {//System.out.println(key + ": " + hm.get(key));}Instant end=Instant.now();System.out.println("KeySet Time use:"+Duration.between(start, end).toMillis());// 2. entrySetstart=Instant.now();for (Entry<String, String> entry : hm.entrySet()) {//System.out.println(entry.getKey() + ": " + entry.getValue());}end=Instant.now();System.out.println("EntrySet Time use:"+Duration.between(start, end).toMillis());// 3. forEachstart=Instant.now();hm.forEach((key, value) -> {//System.out.println(key + ": " + value);});end=Instant.now();System.out.println("Map forEach Time use:"+Duration.between(start, end).toMillis());}}

三、测试结果

从上面的测试结果表可以看出,key_value键值对在数量较少的情况下,keySet和entrySet遍历的效率差别不大,但是数量在10000K时,keySet遍历花费了222ms;entrySet遍历只花费了202ms,可见entrySet比keySet遍历的效率高很多,forEach遍历集合是在Java8中出现的,其效率更190ms高。我建议需要遍历Map时,使用entrySet遍历,JDK8+使用forEach。

四、结果分析

1)keySet():
返回的是只存放key值的Set集合,使用迭代器方式遍历该Set集合,在迭代器中再使用get方法获取每一个键对应的值。使用get方法获取键对应的值时就需要遍历Map集合,主要的差异就在此处。

2)entrySet():
返回的是存放了映射关系的Set集合(一个映射关系就是一个键-值对),就是把(key-value)作为一个整体一对一对地存放到Set集合当中的。然后使用迭代器方式遍历该Set集合就可以取出Map中存放的键值对。

3)Iterator遍历 :

你也可以在keySet和values上应用同样的方法。该种方式看起来冗余却有其优点所在。首先,在老版本java中这是惟一遍历map的方式。另一个好处是,你可以在遍历时调用iterator.remove()来删除entries,另两个方法则不能。根据javadoc的说明,如果在for-each遍历中尝试使用此方法,结果是不可预测的。从性能方面看,该方法类同于for-each遍历的性能。

4)forEach:【jdk8+】

返回的是存放了映射关系的Set集合(一个映射关系就是一个键-值对),就是把(key-value)作为一个整体一对一对地存放到Set集合当中的。然后使用迭代器方式遍历该Set集合就可以取出Map中存放的键值对。

Map遍历KeySet()和EntrySet/ Map.forEach的性能分析相关推荐

  1. java keyset 遍历_Java Map遍历keySet、entrySet速度对比

    第一种遍历方式(采用keySet): HashMap hashmap = new HashMap(); Iterator iterator = hashmap.keySet().iterator(); ...

  2. java keyset entryset 顺序_「entryset」如何遍历Map,map的keySet()和EntrySet()区别 - seo实验室...

    entryset 如何遍历Map,map的keySet()和EntrySet()区别 遍历map public static void main(String[] args) { // TODO Au ...

  3. Java中Map的keySet()、entrySet()详解

    Map中提供了常用方法:keySet().entrySet()等,keySet()方法返回值是Map中key值的集合:entrySet()返回值这个map中各个键值对映射关系的集合,此集合的类型为Ma ...

  4. java map遍历最快_Java Map遍历速度最优解

    第一种: Map map = new HashMap(); Iterator iter = map.entrySet().iterator(); while (iter.hasNext()) { Ma ...

  5. Java中Map的三种遍历方式:keySet、 entrySet、forEach

    前言 最近在看<阿里巴巴Java开发手册(华山版)>,看到了关于Map的遍历方式,手册上写的很详细,我这里用代码再来展示一遍. 代码 public static void main(Str ...

  6. java entryset循环_Java之Map遍历方式性能分析:ketSet 与 entrySet

    keySet():将Map中所有的键存入到Set集合中.因为set具备迭代器,所以可以以迭代方式取出所有的键,再根据get方法获取每一个键对应的值,其仅能通过get()取key. entrySet() ...

  7. Map集合中的两种取出方式keySet和entrySet

    /*map集合中的两种取出方式:1.Set<k> keySet:将map集合中所有的键存入到Set集合,因为Set具备迭代器.所有可用迭代方式取出所有的键,再根据get方法,获取每一个键对 ...

  8. List/Map 遍历

    List 遍历方法有三种: 1. for-each 2. 迭代器 Iterator(ListIterator) 3. for 首选for-each 需要用到迭代器方法时用迭代器,比如next,remo ...

  9. Java的Map遍历

    Map的遍历 private void mapForeach() {Map<String, String> map = new HashMap<>();map.put(&quo ...

  10. Java 集合List、Set、HashMap操作二(Map遍历、List反向、Set删除指定元素,集合只读、TreeMap操作、List转Array、List移动元素)

    Map遍历 import java.util.Map; import java.util.HashMap; import java.util.HashSet; import java.util.Ite ...

最新文章

  1. python 命令行参数-python实现读取命令行参数的方法
  2. 人眼中亮斑的检测、定位和去除(2)
  3. springcloud(十一):服务网关Zuul高级篇
  4. 转先验概率、最大似然估计、贝叶斯估计、最大后验概率
  5. 为踏实上进的【飞鸽传书】开发者而感动
  6. mysql 按周分组_如何在MySQL中按周分组?
  7. Python获取文件后缀名
  8. Vue v-for生成DOM元素
  9. 【运维技术】数据库主从同步搭建
  10. 手机html5测试苹果八,怎么简单质检你的iPhone手机以及真假判断!
  11. 学习云计算需要哪些软件,需要什么知识面?
  12. ESPN:韦德续约狠打LBJ脸 他诠释忠诚大于王权
  13. 计算机组成原理笔记(8)---机器指令、寻址方式
  14. 实现抖音闪烁效果---OpenCV-Python开发指南(54)
  15. vue3 将文字或链接生成二维码 qrcode.vue
  16. 零信任网络安全——软件定义边界SDP技术架构指南
  17. 读书发现一个勘误,提交了,这里是地址
  18. Java行政区划代码处理,包含源JSON文件,处理过后的JSON、Excel、SQL文件
  19. [附源码]Nodejs计算机毕业设计纳雍县梦金园珠宝店管理系统Express(程序+LW)
  20. 团队软件的NABCD—校园知网

热门文章

  1. struts标签 s date 的使用
  2. Java HashSet和ArrayList的查找Contains()时间复杂度
  3. Hbase之过滤器的使用
  4. E - Alignment
  5. spring 13-Spring框架基于Annotation的AOP配置
  6. 每天CookBook之JavaScript-073
  7. Swf Decrypt详解
  8. Python引用复制,参数传递,弱引用与垃圾回收
  9. ubuntu14.04中mysql的安裝及utf8编码集配置
  10. Flex中如何通过设置GridLines对象的horizontalAlternateFill样式交错显示LineSeries图表背景颜色的例子...