在Java中将String拆分为String(包含一些特殊字符)和Integer



我有两个类似字符串的

a 101[newline] 111

需要将这些放在HashMap中,其中字符串[newline]和其他字符串'a'作为键,Integer 111作为键的值。

注意:a和101之间的有效空格。和'[newline]'也应被视为字符串。

使用regex尝试此操作。我认为这会达到你的目的。

public static void main(String[] args) {
String[] s = {"a    101","[newline]      111"};
Map<String, Integer> map = new HashMap<>();
for(int i=0;i<s.length;i++) {
String[] splitedData = s[i].split("\s+");
map.put(splitedData[0], Integer.valueOf(splitedData[1].trim()));
}
for (Map.Entry<String,Integer> entry : map.entrySet())
System.out.println("Key = " + entry.getKey() +
", Value = " + entry.getValue());
}

最新更新