HashMap的遍历:
1.使用map.keyset()与map.values()遍历键值
HashMap<String,Integer> hashMap=new HashMap<>(); hashMap.put("hello",1); hashMap.put("hi",2); for(String a:hashMap.keySet()) { System.out.println(a);//键 } for(Integer integer:hashMap.values()) { System.out.println(integer);//值 }
2.使用entryset()
HashMap<String,Integer> hashMap=new HashMap<>(); hashMap.put("hello",1); hashMap.put("hi",2); for(Map.Entry<String,Integer> a: hashMap.entrySet()) { System.out.println(a.getKey()); System.out.println(a.getValue()); }
3.使用Iterator迭代
HashMap<String,Integer> hashMap=new HashMap<>(); hashMap.put("hello",1); hashMap.put("hi",2); Iterator<Map.Entry<String,Integer>> iterator=hashMap.entrySet().iterator(); while(iterator.hasNext()) { Map.Entry<String,Integer> a=iterator.next(); System.out.println(a.getKey()+a.getValue()); }
原文:https://www.cnblogs.com/mlqq/p/14797628.html