问题
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. I'm little confuse how to apply loop on the hash table and extract values from. Please explain me how to do this. Thanks in advance
public String parseHashtable(Hashtable detailHashtable){
String hashstring= "";
foreach(){
hashstring += key + "=" + hashtable[key] + "|";
}
return hashstring;
}
回答1:
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();
回答2:
You can use Map.Entry as follows:
String hashstring= "";
for (Map.Entry<String, String> entry : hashTable.entrySet()) {
hashstring += entry.getKey() + "=" + entry.getValue() + "|";
}
回答3:
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()
回答4:
public String parseHashtable(Hashtable detailHashtable){
String hashstring= "";
for(Entry<String,String> entry : detailHashtable.entrySet()){
hashstring += entry.getKey() + "=" + entry.getValue() + "| ";
}
return hashstring;
}
回答5:
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();
...
}
回答6:
use entry.getKey().to String() and entry.getValue().toString();
来源:https://stackoverflow.com/questions/32396140/how-to-convert-a-hash-table-in-string-in-java