在java中的map有很多种迭代方式,我们来看一下一些最常用的方式并且看一下他们的优点和缺点,因为java中的map都继承自Map接口,下边的接口适用于实现map接口的所有形式(HashMap、TreeMap、LinkedHashMap和HashTable等等)
Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for (Map.Entry<Integer, Integer> entry : map.entrySet()) { System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); }
Map<Integer, Integer> map = new HashMap<Integer, Integer>(); //在keys上迭代 for (Integer key : map.keySet()) { System.out.println("Key = " + key); } //在values进行迭代 for (Integer value : map.values()) { System.out.println("Value = " + value); }
Map<Integer, Integer> map = new HashMap<Integer, Integer>(); Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator(); while (entries.hasNext()) { Map.Entry<Integer, Integer> entry = entries.next(); System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); }
Map map = new HashMap(); Iterator entries = map.entrySet().iterator(); while (entries.hasNext()) { Map.Entry entry = (Map.Entry) entries.next(); Integer key = (Integer)entry.getKey(); Integer value = (Integer)entry.getValue(); System.out.println("Key = " + key + ", Value = " + value); }
Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for (Integer key : map.keySet()) { Integer value = map.get(key); System.out.println("Key = " + key + ", Value = " + value); }