Java 8:如何将 String 转换为 Map<String,String>?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/52695410/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java 8: How to convert String to Map<String,String>?
提问by Phuong
I have a Map:
我有一张地图:
Map<String, String> utilMap = new HashMap();
utilMap.put("1","1");
utilMap.put("2","2");
utilMap.put("3","3");
utilMap.put("4","4");
I converted it to a String:
我将其转换为字符串:
String utilMapString = utilMap
.entrySet()
.stream()
.map(e -> e.toString()).collect(Collectors.joining(","));
Out put: 1=1,2=2,3=3,4=4,5=5
How to convert utilMapString to Map in Java8? Who can help me with?
如何在 Java8 中将 utilMapString 转换为 Map?谁能帮帮我?
采纳答案by user7
Split the string by ,
to get individual map entries. Then split them by =
to get the key and the value.
拆分字符串,
以获取单个地图条目。然后将它们拆分=
以获取键和值。
Map<String, String> reconstructedUtilMap = Arrays.stream(utilMapString.split(","))
.map(s -> s.split("="))
.collect(Collectors.toMap(s -> s[0], s -> s[1]));
Note:As pointed out by Andreas@ in the comments, this is not a reliable way to convert between a map and a string
注意:正如Andreas@ 在评论中指出的那样,这不是在地图和字符串之间进行转换的可靠方法
EDIT: Thanks to Holger for this suggestion.
编辑:感谢 Holger 的这个建议。
Use s.split("=", 2)
to ensure that the array is never larger than two elements. This will be useful to not lose the contents (when the value has =
)
使用s.split("=", 2)
以确保阵列从来没有超过两个元素大。这对于不丢失内容很有用(当值有时=
)
Example:when the input string is "a=1,b=2,c=3=44=5555"
you will get {a=1, b=2, c=3=44=5555}
示例:当输入字符串为时,"a=1,b=2,c=3=44=5555"
您将得到{a=1, b=2, c=3=44=5555}
Earlier (just using s.split("=")
) will give
{a=1, b=2, c=3}
早些时候(只是使用s.split("=")
)会给
{a=1, b=2, c=3}
回答by Amit
If you want to generate a map from String you can it with below way:
如果您想从 String 生成地图,您可以使用以下方式:
Map<String, String> newMap = Stream.of(utilMapString.split("\,"))
.collect(Collectors.toMap(t -> t.toString().split("=")[0], t -> t.toString().split("=")[1]));
回答by Tim Biegeleisen
Here is another option which streams a list of 1=1
etc. terms into a map.
这是另一个选项,它将等项列表流式传输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}]
回答by Azee
If the sequence may contain values with the same key - use
如果序列可能包含具有相同键的值 - 使用
Map<String, String> skipDuplicatesMap = Stream.of("1=1,2=2,3=3,4=4,5=5".split(",")).
map(el -> el.split("=")).
collect(toMap(arr -> arr[0], arr -> arr[1], (oldValue, newValue) -> oldValue));