java - Iterate through a HashMap

Mots clés : javaloopshashmapiterationjava

meilleur 5 Réponses java - Iterate through a HashMap

vote vote

94

Map<String, Object> map = ...;  for (String key : map.keySet()) {     // ... } 
for (Object value : map.values()) {     // ... } 
for (Map.Entry<String, Object> entry : map.entrySet()) {     String key = entry.getKey();     Object value = entry.getValue();     // ... } 
vote vote

83

public static void printMap(Map mp) {     Iterator it = mp.entrySet().iterator();     while (it.hasNext()) {         Map.Entry pair = (Map.Entry)it.next();         System.out.println(pair.getKey() + " = " + pair.getValue());         it.remove(); // avoids a ConcurrentModificationException     } } 
vote vote

73

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>();  // Iterating over keys only for (Integer key : map.keySet()) {     System.out.println("Key = " + key); }  // Iterating over values only 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); } 
vote vote

61

for (Map.Entry<String, String> item : hashMap.entrySet()) {     String key = item.getKey();     String value = item.getValue(); } 
vote vote

57

Map<?,?> map = new HashMap<Object, Object>(); for(Entry<?, ?> e: map.entrySet()){     System.out.println("Key " + e.getKey());     System.out.println("Value " + e.getValue()); } 
Collection<?> keys = map.keySet(); for(Object key: keys){     System.out.println("Key " + key);     System.out.println("Value " + map.get(key)); } 
Collection<?> values = map.values(); 

Questions similaires