2010-07-27 20 views

risposta

16

Con for-each loop, utilizzare Map.keySet() per chiavi iterazione, Map.values() per valori iterazione e Map.entrySet() per l'iterazione coppie chiave/valore.

Si noti che tutte queste sono viste dirette della mappa che è stata utilizzata per acquisirle quindi qualsiasi modifica apportata a una delle tre o alla mappa stessa si rifletterà anche su tutte le altre.

1
hashmap.keySet().iterator() 

utilizzare un ciclo for per iterarlo.

quindi utilizzare hashmap.get(item) per ottenere valori individuali,

In alternativa basta usare entrySet() per ottenere un iteratore per i valori.

+1

Oppure, a seconda del significato di ping per "valori", 'hashmap.values ​​(). Iterator()'. –

2
for (Map.Entry<T,U> e : map.entrySet()) 
{ 
    T key = e.getKey(); 
    U value = e.getValue(); 
    . 
    . 
    . 
} 

Inoltre, se si utilizza un LinkedHashMap come l'attuazione, si itera nell'ordine sono stati inseriti i coppie chiave/valore. Se ciò non è importante, usa una HashMap.

+0

Risposta molto chiara, grazie –

21

Sì, lo fai ottenendo il numero entrySet() della mappa. Per esempio:

Map<String, Object> map = new HashMap<String, Object>(); 

// ... 

for (Map.Entry<String, Object> entry : map.entrySet()) { 
    System.out.println("key=" + entry.getKey() + ", value=" + entry.getValue()); 
} 

(Naturalmente, sostituire String e Object con i tipi che il vostro particolare Map ha - il codice di cui sopra è solo un esempio).

2
public class abcd { 
    public static void main(String[] args) 
    { 
     Map<Integer, String> testMap = new HashMap<Integer, String>(); 
     testMap.put(10, "a"); 
     testMap.put(20, "b"); 
     testMap.put(30, "c"); 
     testMap.put(40, "d"); 
     for (Entry<Integer, String> entry : testMap.entrySet()) { 
      Integer key=entry.getKey(); 
      String value=entry.getValue(); 
     } 
    } 
}