Java 8:如何将String转换为Map< String,String>? [英] Java 8: How to convert String to Map<String,String>?

查看:2665
本文介绍了Java 8:如何将String转换为Map< String,String>?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张地图:

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

如何在Java8中将utilMapString转换为Map?谁可以帮我?

How to convert utilMapString to Map in Java8? Who can help me with?

推荐答案

将字符串拆分为至获取单独的地图条目。然后用 = 拆分它们以获取密钥和值。

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]));

注意:正如评论中的Andreas @,这不是一种可靠的转换方式在地图和字符串之间

Note: As pointed out by Andreas@ in the comments, this is not a reliable way to convert between a map and a string

编辑
感谢Holger提出此建议。

EDIT: Thanks to Holger for this suggestion.

使用 s.split(=,2)确保数组永远不会超过两个元素。这对于不丢失内容很有用(当值 = 时)

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 =)

示例:当输入字符串a = 1,b = 2,c = 3 = 44 = 5555
时,您将获得 {a = 1,b = 2,c = 3 = 44 = 5555}

早期(仅使用 s.split(=))将给出
{a = 1,b = 2,c = 3}

Earlier (just using s.split("=")) will give {a=1, b=2, c=3}

这篇关于Java 8:如何将String转换为Map&lt; String,String&gt;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆