将字符串拆分为键值对
我有一个这样的字符串:
pet:cat::car:honda::location:Japan::food:sushi
Now 指示键值对,同时分隔这些对。我想将键值对添加到映射中。:
::
我可以使用以下方法实现此目的:
Map<String, String> map = new HashMap<String, String>();
String test = "pet:cat::car:honda::location:Japan::food:sushi";
String[] test1 = test.split("::");
for (String s : test1) {
String[] t = s.split(":");
map.put(t[0], t[1]);
}
for (String s : map.keySet()) {
System.out.println(s + " is " + map.get(s));
}
但是有没有一种有效的方法来做到这一点呢?
我觉得代码效率低下,因为我使用了2个对象并调用了两次函数。另外,我正在使用,如果没有值,可能会抛出一个。String[]
split
t[0]
t[1]
ArrayIndexOutOfBoundsException