PDA

View Full Version : [Java] HashMap e iterazioni


Soel
04-03-2009, 18:48
Salve a tutti.
Avrei bisogno di creare un ciclo che prelevi tutti i valori contenuti in una HashMap e li modifichi, senza tuttavia conoscere il nome di ogni singola chiave della mappa. E' possibile fare una cosa del genere in Java? E se sì, sapreste dirmi come?
Grazie anticipatamente per l'aiuto.

magix2003
04-03-2009, 19:26
entrySet

public Set entrySet()

Returns a collection view of the mappings contained in this map. Each element in the returned collection is a Map.Entry. The collection is backed by the map, so changes to the map are reflected in the collection, and vice-versa. The collection supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Collection.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations.

Specified by:
entrySet in interface Map
Specified by:
entrySet in class AbstractMap

Returns:
a collection view of the mappings contained in this map.
See Also:
Map.Entry




Tratto da: http://java.sun.com/j2se/1.4.2/docs/api/java/util/HashMap.html#entrySet()

Soel
04-03-2009, 20:08
Grazie, ma come faccio ad iterare su un oggetto di tipo Set?

magix2003
04-03-2009, 20:13
Devi utilizzare un iterator:

-> http://java.sun.com/j2se/1.4.2/docs/api/java/util/Set.html#iterator()
-> http://java.sun.com/j2se/1.4.2/docs/api/java/util/Iterator.html

^TiGeRShArK^
04-03-2009, 20:35
o anche il foereach se usi java 5 o superiori che è ben + leggibile:

Map<String, int> map = new HashMap<String, int>();
for (Map.entry<String, int> currentElement : map.entrySet()) {
int value = currentElement.getValue();
}

Soel
05-03-2009, 19:36
Grazie mille!