How to Browse a HashMap in Java

In this tutorial we will use two methods to traverse a HashMap in Java:
  1. Loop for
  2. Loop while + Iterator
In the example below, we are going through the HashMap hash table using both methods: for and iterator inside the while.

import java.util.HashMap; 
import java.util.Iterator;
import java.util.Map;

public class parcoursHashMap {

public static void main(String[] args) {

HashMap< String,Double> map = new HashMap< String,Double> ();

map.put("A",12.0);
map.put("B",42.1);
map.put("C",5.6);
map.put("D",29.7);

//for
System.out.println("for:"loop);
for (Map.Entry mapentry : map.entrySet()) {
System.out.println("key: "+mapentry.getKey()
+ " | value: " + mapentry.getValue());
}

//while+iterator
System.out.println("While loop");
Iterator iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry mapentry = (Map.Entry) iterator.next();
System.out.println("key: "+mapentry.getKey()
+ " | value: " + mapentry.getValue());
}
}
}
Runtime:

Loop for:
Key: D | Value: 29.7
Key: A | Denomination: 12.0
Key: B | Denomination: 42.1
Key: C | value: 5.6
Loop while
Key: D | Value: 29.7
Key: A | Denomination: 12.0
Key: B | Denomination: 42.1
Key: C | value: 5.6
In both cases, the key-value data set is retrieved from the object Map.Entry. In the for loop, we used the method entrySet() of the Map class. In the while loop, we retrieved an Iterator object and after getting the key-value set, then we put a cast in Map.Entry to print the keys and values with both methods getKey() and getValue().

References:
HashMap Traverse
Interface Iterator Javadoc

Commentaires (12)

Connectez-vous pour commenter

Rejoignez la discussion et partagez vos connaissances avec la communauté

JD
Jean Dupont Il y a 2 heures

Excellent tutoriel ! J'ai enfin compris comment utiliser Apache POI correctement.

👍 12 Répondre Signaler
CodeurJava ✓ Auteur • Il y a 1 heure

Merci Jean ! N'hésitez pas si vous avez des questions.