Skip to content

Instantly share code, notes, and snippets.

@jesty
Last active February 26, 2016 16:46
Show Gist options
  • Save jesty/6979eb90189292551e91 to your computer and use it in GitHub Desktop.
Save jesty/6979eb90189292551e91 to your computer and use it in GitHub Desktop.
This is a quick and dirty utility class to transform some keys that use dot notation (i.e. properties file keys) to a hierarchical structure like a java.util.Map. Usefull to transform a properties file to a json
import java.util.HashMap;
import java.util.Map;
/*
* This is a quick and dirty utility class to transform some keys
* that use dot notation (i.e. properties file keys) to a hierarchical
* structure like a java.util.Map.
* Usefull to transform a properties file to a json.
*/
public class DotNotationToMap
{
/* returns {a: {
b: {
c: "uno",
d: "due"
},
e: "tre"
},
f: "quattro"
}
*/
public Map<String, Object> example()
{
Map<String, Object> map = new HashMap<>();
put(map, "a.b.c", "uno");
put(map, "a.b.d", "due");
put(map, "a.e", "tre");
put(map, "f", "quattro");
return map;
}
private void put(Map<String, Object> map, String path, String value)
{
String[] split = path.split("\\.");
Map<String, Object> newMap = map;
int i = 0;
int n = split.length;
for (String s : split)
{
if (i == n - 1)
{
newMap.put(s, value);
} else
{
Object o = newMap.get(s);
if (o == null)
{
newMap.put(s, new HashMap<String, Object>());
}
newMap = (Map<String, Object>) newMap.get(s);
}
i++;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment