How to list Hashtable keys and values?

I have a problem; I have some data and I display it with a Hashtable for example, I write:

  Enumeration keys; keys=CellTraffic_v.elements(); while(keys.hasMoreElements()) outputBuffer.append(keys.nextElement()+"\n\n"); 

but he only shows me meanings, how can I show values ​​and keys together? for example this

if my key is "A" and my value is "B", show me this:

 AB 

Thanks...

+7
java hashtable
source share
3 answers

Do you have a key Use the key to get the value from the map, and you have all the mappings. For example, in Java with String as type for a key:

 for (String key : map.keySet()) { System.out.println(key + ":" + map.get(key)); } 

.

+7
source share

Hashtable implements Map . The Map.entrySet function returns a collection ( Set ) of Map.Entry instances that have the getKey and getValue .

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 entries in a Hashtable, you can use templates to eliminate the above toString calls. For example, entry could be declared Map.Entry<String,String> if your Hashtable is declared Hashtable<String,String> .

If you can combine templates with generics, this is just short:

 for (Map.Entry<String,String> entry : yourTable.entrySet()) { System.out.println(entry.getKey() + " " + entry.getValue()); } 

This assumes yourTable is Hashtable<String,String> . It just goes to show how far Java has gone over the past few years, in many ways, without losing its substantial Java version.

Slightly OT: If you don't need synchronization, use a HashMap instead of a Hashtable . If you do, use ConcurrentHashMap (thanks, akappa!).

+18
source share

entrySet () returns an enumeration of values ​​in a Hashtable.
keySet () returns an enumeration of keys in a Hashtable.
entrySet () returns records (key and value) as a set

 for( Iterator iter=hash.keySet().iterator(); iter.hasNext(); ) { String key = (String) iter.next(); String value = (String) hash.get( key ); } for( Iteration iter=hash.entrySet().iterator(); iter.hasNext(); ) { Map.Entry entry = (Map.Entry) iter.next(); String key = (String) entry.getKey(); String value = (String) entry.getValue(); } 

or using generics, in which case your hash is HashMap <String, String>

 for( String key : hash.keySet() ) { String value = hash.get( key ); } for( Map.Entry entry : hash.entrySet() ) { String key = entry.getKey(); String value = entry.getValue(); } 
+1
source share

All Articles