I have a problem ; I have some data and I show it with Hashtable
for example I write :
Enumeration keys;
keys=CellTraffic_v.elements();
while(keys.hasMoreElements())
outputBuffer.append(keys.nextElement()+"\n\n");
but it show me just values how can i show values and keys together? for example this
if my key be "A" and my value be "B" show me this :
A B
Thanks ...
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!).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With