How to Convert String to Map in Java

Convert String to Map in Java

In this example, we will show you simple program about, how to convert string to map in Java. The example program has been tested and verified, the same has been shared in the post.

Example Program

package com.dineshkrish;

import java.io.IOException;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * 
 * @author Dinesh Krishnan
 *
 */

public class Example {

	public static Map<String, String> convert(final String mapStr) throws IOException {

		Map<String, String> map = new HashMap<>();

		// converting string to properties object
		Properties props = new Properties();
		props.load(new StringReader(mapStr.substring(1, mapStr.length() - 1).replace(", ", "\n")));

		// iterating properties to put value to map
		for (Map.Entry<Object, Object> e : props.entrySet()) {
			map.put((String) e.getKey(), (String) e.getValue());
		}

		return map;
	}
	
	public static void main(String[] args) {
		
		Map<String, String> map = new HashMap<String, String>();
		
		map.put("1", "One");
		map.put("2", "One");
		map.put("3", "One");
		map.put("4", "One");
		map.put("5", "One");
		
		// map to string
		String mapStr = map.toString();
		
		System.out.println("string map : "+mapStr);
		
		try {
			
			// converting string to map
			Map<String, String> myMap = convert(mapStr);
			
			System.out.println("object map : "+myMap);
			
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println(e.getMessage());
		}
		
	}

}

Output

string map : {1=One, 2=One, 3=One, 4=One, 5=One}
object map : {1=One, 2=One, 3=One, 4=One, 5=One}

References

1. https://docs.oracle.com/javase/8/docs/api/java/util/Map.html
2. https://docs.oracle.com/javase/8/docs/api/java/util/Properties.html
3. https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html

Hello, folks, I am a founder of dineshkrish.com. I love Java and Open source technologies, If you find my tutorials are useful, please consider making donations to these charities.