[英]Java Map<String, Map<String, Object>> convert to String and back
[英]How to convert mixed map string back to mixed map in Java
我有一个混合地图,如: private Map<Integer, Map<Character, Float>> probabilities = new HashMap<>();
作为字符串的输出是: this.probabilities.toString() => {0={a=0.5}, 1={s=0.75}, 2={ =1.0}}
那么我有没有办法像以前一样将此输出转换为混合地图?
请记住,我可以拥有任何类型的字符,例如“}”,最终可能看起来像:
{0={a=0.25}, 1={"=0.5}, 2={s=0.625}, 3={{=0.75}, 4={ =0.875}, 5={}=1.0}}
这是一种将该字符串解析回嵌套映射的方法。
static Map<Integer, Map<Character, Float>> parse(String input) {
if (! input.startsWith("{") || ! input.endsWith("}"))
throw new IllegalArgumentException("Invalid input (missing surrounding '{}'): " + input);
Map<Integer, Map<Character, Float>> output = new LinkedHashMap<>();
Matcher m = Pattern.compile("\\G(\\d+)=\\{(.)=([0-9.]+)\\}(?:, |$)")
.matcher(input).region(1, input.length() - 1);
int end = 1;
while (m.find()) {
output.computeIfAbsent(Integer.valueOf(m.group(1)), k -> new LinkedHashMap<>())
.put(m.group(2).charAt(0), Float.valueOf(m.group(3)));
end = m.end();
}
if (end != input.length() - 1)
throw new IllegalArgumentException("Invalid input at: " + input.substring(end));
return output;
}
测试
Map<Integer, Map<Character, Float>> probabilities = new TreeMap<>(Map.of(
0, Map.of('a', 0.25f),
1, Map.of('"', 0.5f),
2, Map.of('s', 0.625f),
3, Map.of('{', 0.75f),
4, Map.of('�', 0.875f),
5, Map.of('}', 1.0f)
));
System.out.println("probabilities = " + probabilities);
String input = "{0={a=0.25}, 1={\"=0.5}, 2={s=0.625}, 3={{=0.75}, 4={�=0.875}, 5={}=1.0}}";
System.out.println("input = " + input);
Map<Integer, Map<Character, Float>> output = parse(input);
System.out.println("output = " + output);
输出
probabilities = {0={a=0.25}, 1={"=0.5}, 2={s=0.625}, 3={{=0.75}, 4={�=0.875}, 5={}=1.0}}
input = {0={a=0.25}, 1={"=0.5}, 2={s=0.625}, 3={{=0.75}, 4={�=0.875}, 5={}=1.0}}
output = {0={a=0.25}, 1={"=0.5}, 2={s=0.625}, 3={{=0.75}, 4={�=0.875}, 5={}=1.0}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.