Reputation: 910
I'm new in Java and I want to convert a hash table in the form of a string, with each pair separated by any special character. How can I apply loop on the hash table and extract values from?
public String parseHashtable(Hashtable detailHashtable){
String hashstring= "";
foreach(){
hashstring += key + "=" + hashtable[key] + "|";
}
return hashstring;
}
Upvotes: 0
Views: 5142
Reputation: 1003
public String parseHashtable(Hashtable detailHashtable){
String hashstring= "";
for(Entry<String,String> entry : detailHashtable.entrySet()){
hashstring += entry.getKey() + "=" + entry.getValue() + "| ";
}
return hashstring;
}
Upvotes: 1
Reputation: 1032
String seperator = "|";
StringBuilder sb = new StringBuilder();
Set<String> keys = detailHashtable.keySet();
for(String key: keys) {
sb.append(key+"="+detailHashtable.get(key)+ seperator);
}
return sb.toString();
Upvotes: 2
Reputation:
Map
from which Hashtable
extends provides the method Map.entrySet()
, which returns a set containing all entries in the map.
for(Map.Entry e : detailHashTable.entrySet()){
Object key = e.getKey();
Object value = e.getValue();
...
}
Upvotes: 0
Reputation: 5786
Both the HashMap
and HashTable
can use Map.Entry
to get both key and value simultaneously.
String hashstring= "";
for (Map.Entry<String, String> entry : detailHashtable.entrySet()) {
hashstring += entry.getKey() + "=" + entry.getValue() + "|";
}
Refer the API to know what operations can be used. http://docs.oracle.com/javase/7/docs/api/java/util/Hashtable.html#entrySet()
Upvotes: 1
Reputation: 1513
You can use Map.Entry as follows:
String hashstring= "";
for (Map.Entry<String, String> entry : hashTable.entrySet()) {
hashstring += entry.getKey() + "=" + entry.getValue() + "|";
}
Upvotes: 4