How do I enumerate the keys and values of a Hashtable?
I have a problem ; I have some data and I show it with Hash开发者_如何学JAVAtable
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!).
You have the key right? Use the key to get the value out of the map, and you have all the mappings. For example in Java with String as type for key:
for (String key : map.keySet()) {
System.out.println(key + ":" + map.get(key));
}
.
entrySet() returns an enumeration of the values in the Hashtable.
keySet() returns an enumeration of the keys in the Hashtable.
entrySet() returns the entries (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 a 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();
}
精彩评论