Hashtable
implements Map
. The Map.entrySet
function returns a collection (Set
) of Map.Entry
instances, which have getKey
and getValue
methods.
So:
Iterator<Map.Entry> it;
Map.Entry entry;
it = yourTable.entrySet().iterator();
while (it.hasNext()) {
entry = it.next();
System.out.println(
entry.getKey().toString() + " " +
entry.getValue().toString());
}
If you know the types of the entries in the Hashtable, you can use templates to eliminate the toString
calls above. For instance, entry
could be declared Map.Entry<String,String>
if your Hashtable is declared Hashtable<String,String>
.
If you can combine templates with generics, it's downright short:
for (Map.Entry<String,String> entry : yourTable.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
That assumes yourTable
is a Hashtable<String,String>
. Just goes to show how far Java has come in the last few years, largely without losing its essential Java-ness.
Slightly OT: If you don't need the synchronization, use HashMap
instead of Hashtable
. If you do, use a ConcurrentHashMap
(thanks, akappa!).