我有一个地图:
Map<String, String> utilMap = new HashMap();
utilMap.put("1","1");
utilMap.put("2","2");
utilMap.put("3","3");
utilMap.put("4","4");
我把它转换成字符串:
String utilMapString = utilMap
.entrySet()
.stream()
.map(e -> e.toString()).collect(Collectors.joining(","));
Out put: 1=1,2=2,3=3,4=4,5=5
如何utilMapString转换为地图中Java8?谁可以帮我?
拆分字符串通过,
获得单独的地图项。然后,通过将它们分割=
得到键和值。
Map<String, String> reconstructedUtilMap = Arrays.stream(utilMapString.split(","))
.map(s -> s.split("="))
.collect(Collectors.toMap(s -> s[0], s -> s[1]));
注:正如指出的安德烈亚斯@在评论,这不是一张地图和一个字符串之间进行转换的可靠途径
编辑:感谢霍尔格这一建议。
使用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}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句