How to Browse a HashMap in Java
In this tutorial we will use two methods to traverse a HashMap in Java:- Loop for
- 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:
References:
HashMap Traverse
Interface Iterator Javadoc
Loop for: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().
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
References:
HashMap Traverse
Interface Iterator Javadoc