Andrain
Andrain

Reputation: 910

How to convert a hash table in string in Java

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

Answers (6)

Jib'z
Jib'z

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

McNultyyy
McNultyyy

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

shubham
shubham

Reputation: 41

use entry.getKey().to String() and entry.getValue().toString();

Upvotes: 0

user4668606
user4668606

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

Karthik R
Karthik R

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

Rahul Yadav
Rahul Yadav

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

Related Questions