Java - Browse Hashtable with Iterator

In this example we will see how to browse Hashtable using Iterator. The advantage of Iterator is the separation between key and value for each peer. Therefore, we can display the keys and values independently.

Example
The methods used and explained in the program below.

javacoder package. Hashtable; 
import java.util.Hashtable;
import java.util.Set;
import java.util.Iterator;

public class IterateHashtable {

public static void main(String[] args) {

// Creating the Hashtable
Hashtable hashtable = new Hashtable();

/*
* add key-value peers to Hashtable
* public V put(K key, V value):bind key to value
* keys and values must not be null
*/
hashtable.put("1", "v1");
hashtable.put("2", "v2");
hashtable.put("3", "v3");
hashtable.put("4", "v4");
hashtable.put("5", "v5");

System.out.println("Display:");

/*public Set keySet():returns a set of keys
* in this map. This set is returned by the map
* so a change in the map is reflected in the set
* and vice-to-that
*
*/
Set keys = hashtable.keySet();

//get an iterator of the keys
Iterator itr = keys.iterator();

String key="";
//display of key-value peers
while (itr.hasNext()) {
// get the key
key = itr.next();

/*public V get(Object key): returns the corresponding value
* to the key, otherwise null if the map contains no matching value
*
*/
System.out.println("Key: "+key+" & Value: "+hashtable.get(key));
}
}
}
Runtime:

Display:
Key: 5 & Value: v5
Key: 4 & Value: v4
Key: 3 & Value: v3
Key: 2 & Value: v2
Key: 1 & Value: v1

Resources:
https://docs.oracle.com/javase/7/docs/api/java/util/Hashtable.html
https://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html