In questo post vengono sinteticamente presentati i diversi metodi che sono messi a disposizione dal linguaggio java per iterare gli elementi di un oggetto che implementa l’interfaccia java.util.Map
. Come noto questo tipo di interfaccia ha come scopo quello di consentire un mapping tra coppie chiave-valore. Inoltre ed è specificatamente pensato per essere efficiente nelle operazioni di inserimento e lettura.
Metodo 1: Iterazione sugli Elementi Map.Entry
L’interfaccia Entry
rappresenta una coppia chiave-valore contenuta in una mappa ed il metodo entrySet()
di java.util.Map
restituisce una collezione iterabile di tutti gli oggetti contenuti nella mappa. Questo significa che è possibile iterare tutte le entry attraverso un semplice ciclo for-each:
1 2 3 4 5 |
public static void method1( Map<String, Integer> map ) { for (Map.Entry<String, Integer> entry : map.entrySet()) { System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); } } |
Metodo 2: Iterazione sulle Chiavi/Valori
L’interfaccia java.util.Map
prevede due metodi keySet()
e values()
che consentono rispettivamente di ottenere una collection di tutte le chiavi o di tutti i valori, attraverso le quali è poi possibile iterare mediante un ciclo for-each:
1 2 3 4 5 6 7 8 9 10 11 |
public static void method2( Map<String, Integer> map ) { //iterating over keys only for (String key : map.keySet()) { System.out.println("Key = " + key); } //iterating over values only for (Integer value : map.values()) { System.out.println("Value = " + value); } } |
Metodo 3: Iterazione Attraverso Iterator
Nel metodo 1 abbiamo ottenuto la collection di tutte le entry della mappa attraverso il metodo entrySet()
. La collection restituita implementa l’interfaccia Iterable
la quale definisce il metodo iterator()
che restituisce un oggetto di tipo Iterator
. Tale oggetto consente di eseguire un ciclo sugli elementi della collection da cui è stato ottenuto ed in particolare implementa due metodi hasNext()
e next()
che consentono rispettivamente di determinare se ci sono ancora elementi della collection da ispezionati e di recuperare l’elemento corrente. Attraverso l’utilizzo combinato di tali metodo è possibile iterare le coppie chiave valore della mappa attraverso un ciclo while:
1 2 3 4 5 6 7 |
public static void method3( Map<String, Integer> map ) { Iterator<Map.Entry<String, Integer>> entries = map.entrySet().iterator(); while (entries.hasNext()) { Map.Entry<String, Integer> entry = entries.next(); System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); } } |
Metodo 4: Iterare le Chiavi e Recuperare i Valori
Forse il metodo di iterazione più utilizzato che consiste nell’iterare sulle chiavi ottenute attraverso il metodo keySet()
e recuperare il valore associato alla chiave corrente invocando il get()
sulla mappa:
1 2 3 4 5 6 |
public static void method4( Map<String, Integer> map ) { for (String key : map.keySet()) { Integer value = map.get(key); System.out.println("Key = " + key + ", Value = " + value); } } |
Metodo 4: Utilizzando l’Istruzione forEach
Disponibile solamente a partire dalla versione 8 di java l’interfaccia java.util.Map
prevede un metodo forEach()
che consente di specificare una azione da eseguire su tutti gli elementi della mappa. Il metodo richiede in input un oggetto che implementi l’interfaccia funzionale BiConsumer
, la quale rappresenta un’operazione che accetta due argomenti di input, ovvero la chiave ed il valore dell’entry corrente della mappa, e restituisce un valore di output. L’iterazione sugli elementi della mappa si può scrivere quindi nel seguente modo:
1 2 3 |
public static void method5( Map<String, Integer> map ) { map.forEach((k,v)->System.out.println("Key = " + k + ", Value = " + v)); } |
Conclusioni
Concludiamo implementando il semplice metodo main()
che invoca in successione i metodi appena definiti:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
public static void main(String[] args) { Map<String, Integer> map = new HashMap<String, Integer>(); map.put( "first", 1 ); map.put( "second", 2 ); map.put( "third", 3 ); System.out.println( "-- Method #1 --" ); method1( map ); System.out.println( "-- Method #2 --" ); method2( map ); System.out.println( "-- Method #3 --" ); method3( map ); System.out.println( "-- Method #4 --" ); method4( map ); System.out.println( "-- Method #5 --" ); method5( map ); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
-- Method #1 -- Key = third, Value = 3 Key = first, Value = 1 Key = second, Value = 2 -- Method #2 -- Key = third Key = first Key = second Value = 3 Value = 1 Value = 2 -- Method #3 -- Key = third, Value = 3 Key = first, Value = 1 Key = second, Value = 2 -- Method #4 -- Key = third, Value = 3 Key = first, Value = 1 Key = second, Value = 2 -- Method #5 -- Key = third, Value = 3 Key = first, Value = 1 Key = second, Value = 2 |
Codice Sorgente
Il codice sorgente con tutti gli esempi mostrati è scaricabile qui iterate-map.