while (iter.hasNext()) { Object key = iter.next(); Object val = map.get(key); } 效率低,以后尽量少使用! HashMap的遍历有两种常用的方法,那就是使用keyset及entryset来进行遍历,但两者的遍历速度是有差别的,下面请看实例: public class HashMapTest { public static void main(String[] args) ......
Iterator<Map.Entry<String,Integer>>iterator=map.entrySet().iterator();while(iterator.hasNext()){Map.Entry<String,Integer>entry=iterator.next();// 获取下一个元素System.out.println(entry.getKey()+": "+entry.getValue());// 输出键值对}// 使用Iterator遍历HashMap,灵活,但代码相对复杂。 1. 2....
最基本的Map遍历方式是使用entrySet()方法,通过迭代器或增强型for循环遍历Map中的键值对。 Map<String, Integer> myMap = new HashMap<>(); myMap.put("a", 1); myMap.put("b", 2); for (Map.Entry<String, Integer> entry : myMap.entrySet()) { System.out.println("Key: " + entry.getKey...
public static void main(String[] args) { map = new HashMap<Object, Object>(); for (int i = 0; i < 1000000; i++) { map.put("map" + i, i); } // 第一种: Iterator<Entry<Object, Object>> iter = map.entrySet().iterator(); begin = System.currentTimeMillis(); while (iter....
(1)HashMap遍历 接下来我们来看每种遍历方式的具体实现代码。 package com.tset.three;import java.util.HashMap;import java.util.Iterator;import java.util.Map;/*** @author :caizhengjie* @description:TODO* @date :2021/7/24 11:00 下午*/public class TestMap {public static void main(String[] ...
1、HashMap 初始化的文艺写法 HashMap 是一种常用的数据结构,一般用来做数据字典或者 Hash 查找的容器。普通青年一般会这么初始化: HashMapmap = new HashMap(); map.put("Name", "June"); map.put("QQ", "2572073701"); 看完这段代码,很多人都会觉得这么写太啰嗦了,对此,文艺青年一般这么来了: ...
Map<String,String>map=newHashMap<String,String>();Stringkey,value;for(inti=1;i<=num;i++){key=""+(i*50);value="value"+key;map.put(key,value);} 3、场景测试 3.1遍历key+value 1)keySet利用Iterator遍历 longstartTime1=System.currentTimeMillis();Iterator<String>iter=map.keySet().iterator...
public static void main(String[] args) { HashMap<Integer, String> map = new HashMap<>();map...