Comment parcourir une Hashmap en Java
Dans ce tutoriel nous allons découvrir comment parcourir une Hashmap en Java, en utilisant les méthodes suivantes:
Exemple: Parcourir une Hashmap en utilisant la boucle For
import java.util.*;
public class Main
{
public static void main(String args[])
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
// ajouter des éléments au HashMap
map.put(1, "Alex");
map.put(2, "Emily");
map.put(3, "Thomas");
map.put(4, "Yohan");
//Parcourir le Hashmap avec la boucle For
for (Map.Entry m : map.entrySet()) {
System.out.println("ID: "+m.getKey()+", Nom: "+m.getValue());
}
}
}
Sortie:
ID: 1, Nom: Alex ID: 2, Nom: Emily ID: 3, Nom: Thomas ID: 4, Nom: Yohan
Exemple: Parcourir une Hashmap en utilisant la boucle While avec Iterator
import java.util.*;
public class Main
{
public static void main(String args[])
{
HashMap<Integer, String> map = new HashMap<Integer, String>();
// ajouter des éléments au HashMap
map.put(1, "Alex");
map.put(2, "Emily");
map.put(3, "Thomas");
map.put(4, "Yohan");
//Parcourir le Hashmap avec la boucle While + Iterator
Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry m = (Map.Entry) it.next();
System.out.println("ID: "+m.getKey()+", Nom: "+m.getValue());
}
}
}
Sortie:
ID: 1, Nom: Alex ID: 2, Nom: Emily ID: 3, Nom: Thomas ID: 4, Nom: Yohan

