TomRed.net

  • Increase font size
  • Default font size
  • Decrease font size
Subscribe Bookmark and Share
Home Tutorials JavaScript Java HashMap toString and back to HashMap

Java HashMap toString and back to HashMap

User Rating: / 0
PoorBest 

Every now and then I have to save a HashMap to a database or something and the most sensible way is to use the toString() method which gives a comma separated, equals delimited name value pair string, e.g. {name=bob,address=somewhere,phone=00-353-01-9875666}.  This is useful for logging also (or audit trails).  The problem arises when you want to read that string to a HashMap again.  There is no native function to accomplish this.

I have outlined a simple method below which will accomplish this.  

/**
 * Converts a HashMap.toString() back to a HashMap
 * @param text
 * @return HashMap
 */
protected HashMap convertToStringToHashMap(String text){
	HashMap data = new HashMap();
	Pattern p = Pattern.compile("[\\{\\}\\=\\, ]++");
	String[] split = p.split(text);
	for ( int i=1; i< split.length; i+=2 ){
		data.put( split[i], split[i+1] );
	}
	return data;
}

Essentially we take the string as a parameter and using the pattern we split the string into name value pairs, with the name as split[i] and the value as split[i+1].  We then use the HashMap.put() to add the pair back into the HashMap.  The whole logic of this resides in the Pattern which is a simple regular expression, that shows to split by the '=' in side '{}'.

I hope you have found this useful.  If you have any questions please leave a comment or email support[@]tomred.net