java - 如何在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}}
推荐阅读
- python - 在不创建新列的情况下对数据框列执行计算
- c# - 如何计算具有特定值的 XML 标记以生成摘要 C#;ASP.NET
- c++ - 如何在 C++ 中录制具有精确帧时间戳的视频
- selenium - 用于自动化的无头浏览器的区别
- npm - package.json 中的主键是强制性的吗?
- php - 一旦输入为两位数,PHP/MySQL 查询将不会返回数据
- linux - Linux git clone 问题 - 提示输入密码
- python-3.x - python pathlib operator '/' - 它是如何做到的?
- microsoft-graph-api - WebApi 访问 Exchange 邮箱文件夹 Calendar,Notes,Tasks
- python - Python Speech Recognizer TypeError:“float”和“NoneType”的实例之间不支持“>”