JAVA遍历Map对象的四种方式
方式一:这是最常见的并且在大多数情况下也是最可取的遍历方式。在键值都需要时使用。
1 Mapmap = new HashMap (); 2 map.put(1,"a"); 3 map.put(2,"b"); 4 map.put(3,"ab"); 5 map.put(4,"ab"); 6 map.put(4,"abc"); 7 map.put(4,"abcd"); 8 9 for (Map.Entry entry : map.entrySet()) {10 System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());11 }
方式二: 在for-each循环中遍历keys或values
如果只需要map中的键或者值,你可以通过keySet或values来实现遍历,而不是用entrySet。
1 Mapmap = new HashMap (); 2 //遍历map中的键 3 for (Integer key : map.keySet()) { 4 System.out.println("Key = " + key); 5 } 6 //遍历map中的值 7 for (Integer value : map.values()) { 8 System.out.println("Value = " + value); 9 }
方法三:使用Iterator遍历
使用泛型:
1 Iterator> entries = map.entrySet().iterator();2 while (entries.hasNext()) {3 Map.Entry entry = entries.next();4 System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());5 }
不使用泛型:
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); }
方法四:通过键找值遍历(效率低)
Mapmap = new HashMap (); for (Integer key : map.keySet()) { Integer value = map.get(key); System.out.println("Key = " + key + ", Value = " + value);