Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I enumerate the keys and values of a Hashtable?

Tags:

java

hashtable

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 ...

like image 286
Freeman Avatar asked Feb 07 '10 07:02

Freeman


1 Answers

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!).

like image 174
T.J. Crowder Avatar answered Oct 20 '22 15:10

T.J. Crowder