3 回答

TA貢獻1998條經驗 獲得超6個贊
拆分字符串,
以獲取單個地圖條目。然后將它們拆分=
以獲取鍵和值。
Map<String, String> reconstructedUtilMap = Arrays.stream(utilMapString.split(",")) .map(s -> s.split("=")) .collect(Collectors.toMap(s -> s[0], s -> s[1]));
注意:正如Andreas@ 在評論中指出的那樣,這不是在地圖和字符串之間進行轉換的可靠方法
編輯:感謝 Holger 的這個建議。
使用s.split("=", 2)
以確保陣列從來沒有超過兩個元素大。這對于不丟失內容很有用(當值有時=
)
示例:當輸入字符串為時,"a=1,b=2,c=3=44=5555"
您將得到{a=1, b=2, c=3=44=5555}
早些時候(只是使用s.split("=")
)會給 {a=1, b=2, c=3}

TA貢獻1872條經驗 獲得超4個贊
這是另一個選項,它將等項列表流式傳輸1=1到地圖中。
String input = "1=1,2=2,3=3,4=4,5=5";
Map<String, String> map = Arrays.asList(input.split(",")).stream().collect(
Collectors.toMap(x -> x.replaceAll("=\\d+$", ""),
x -> x.replaceAll("^\\d+=", "")));
System.out.println(Collections.singletonList(map));
[{1=1, 2=2, 3=3, 4=4, 5=5}]

TA貢獻1818條經驗 獲得超8個贊
如果您想從 String 生成地圖,您可以使用以下方式:
Map<String, String> newMap = Stream.of(utilMapString.split("\\,")) .collect(Collectors.toMap(t -> t.toString().split("=")[0], t -> t.toString().split("=")[1]));
添加回答
舉報