how to convert a hash table in string in java

天大地大妈咪最大 提交于 2020-01-16 10:03:29

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!