[英]How to split the following string using Java?
How do I go about splitting the following string using Java? 如何使用Java分割以下字符串?
{525={174=2, 133=1, 182=1}}
There can be multiple lines similar to above. 可能有与上面相似的多行。 Each of them is a combination for the outer HashMap.
它们每个都是外部HashMap的组合。 Assuming there is another line
假设还有另一条线
{500={100=2, 150=1, 200=1}}
The desired structure would be 所需的结构将是
525 -> 174 -> 2
133 -> 1
182 -> 1
500 -> 100 -> 2
150 -> 1
200 -> 1
I want to have the numbers in a Hashmap>. 我想在Hashmap>中包含数字。
Here is what I tried: 这是我尝试过的:
String s="{525={174=2, 133=1, 182=1}}";
HashMap<Integer, HashMap<Integer, Integer>> fullMap = new HashMap<Integer, HashMap<Integer, Integer>>();
Integer key, innerKey, innerValue;
key = Integer.parseInt(s.split("=")[0].replace("{",""));
I'm new to Java and don't know how to proceed further. 我是Java的新手,不知道如何进一步进行。
try this 尝试这个
String[] a = s.replaceAll("[{}]", "").split("=", 2);
int key = Integer.parseInt(a[0].trim());
HashMap<Integer, Integer> innerMap = new HashMap<>();
for (String e : a[1].split(",")) {
a = e.split("=");
innerMap.put(Integer.parseInt(a[0].trim()), Integer.parseInt(a[1].trim()));
}
fullMap.put(key, innerMap);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.