去评论
爱生活

HashMap的几种遍历方式,hashmap怎么遍历

123
2022/04/13 23:48:01

HashMap的几种遍历方式


有两种第一种: Map map = new HashMap(); Iterator iter = map.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); Object key = entry.getKey(); Object val = entry.getValue(); } 效率高,以后一定要使用此种方式!第二种: Map map = new HashMap(); Iterator iter = map.keySet().iterator(); while (iter.hasNext()) { Object key = iter.next(); Object val = map.get(key); } 效率低,以后尽量少使用! HashMap的遍历有两种常用的方法,那就是使用keyset及entryset来进行遍历,但两者的遍历速度是有差别的,下面请看实例: public class HashMapTest { public static void main(String[] args) ...{ HashMap hashmap = new HashMap(); for (int i = 0; i < 1000; i ) ...{ hashmap.put("" i, "thanks"); } long bs = Calendar.getInstance().getTimeInMillis(); Iterator iterator = hashmap.keySet().iterator(); while (iterator.hasNext()) ...{ System.out.print(hashmap.get(iterator.next())); } System.out.println(); System.out.println(Calendar.getInstance().getTimeInMillis() - bs); l……

java中怎么遍历HashMap
一. HashMap staff = new HashMap(); 添加关键字值对,自己写 遍历 Set entries = staff.entrySet(); Iterator iter = entries.iterator(); while(iter.hasNext()) { Map.Entry entry = (Map.Entry)iter.next(); Object key = entry.getKey();得...

关于hashmap遍历问题?
代码解释 ``` ` ```` // 一、第一种写法 HashMap hashMap = new HashMap(); for (Map.Entry en : hashMap.entrySet()) { } // 由于HashMap没加泛型,所以得到的Set也是没有泛型的 Set set = hashMap.entrySet(); // 由于Set没有泛型,程序不知道...

HashMap和List遍历方法总结及如何遍历删除
(一)List的遍历方法及如何实现遍历删除 我们造一个list出来,接下来用不同方法遍历删除,如下代码: List list= new ArrayList();famous.add("zs");famous.add("ls");famous.add("ww");famous.add("dz"); 1、for循环遍历list: for(int i=0;i=...

在java中,遍历hashmap用什么方法
public class MapTest { public static void main(String[] args) { //先来一个map Map map=new HashMap(){{//匿名内部类初始化 put("breakfast", "早点"); put("lunch", "中饭"); put("supper", "晚点"); }}; //遍历方法1:利用keyset进行遍历,...

Java hashMap遍历
HashMap中的元素存储顺序是随机的,所以输出的顺序也是随机的。 for(Map.Entry m:temp.entrySet())进行的遍历 也是随机输出的,你如果需要顺序, 建议使用LinkedHashMap