将字符串在Java中分割为部分以放入映射中。

huangapple go评论78阅读模式
英文:

Split string into parts in java to put it in a map

问题

我一直在尝试从字符串中获取所有的值,并以以下方式将它们放入映射中:

所以,我有一个像这样的字符串:

String cookies = "i=lol;haha=noice;df3=ddtb;"

到目前为止,我一直在尝试这样做:

final Map<String, String> map = new HashMap<>();
map.put(cookies.split(";")[0].split("=")[0], cookies.split(";")[0].split("=")[1]);

但这种方式只能放入一个值,而且非常冗长和难看。是否有使用正则表达式或循环来实现这个的方法?

英文:

I have been trying to get all the values from a string and put them in a map in the following manner:

So I have a string which is like this:

String cookies = &quot;i=lol;haha=noice;df3=ddtb;&quot;

So far I have been trying this out:

final Map&lt;String, String&gt; map = new HashMap&lt;&gt;();
map.put(cookies.split(&quot;;&quot;)[0].split(&quot;=&quot;)[0], cookies.split(&quot;;&quot;)[0].split(&quot;=&quot;)[1]);

But this way I can only put one value in and it is quite long and ugly. Is there any was to due this with regex or a loop?

答案1

得分: 7

你可以使用循环来迭代键值对并将它们放入映射中:

String[] cookieArr = cookies.split(";");
for (String cookieString : cookieArr) {
  String[] pair = cookieString.split("=");
  if (pair.length < 2) {
    continue;
  }
  map.put(pair[0], pair[1]);
}

这里的 if 语句仅用于防止 cookie 字符串格式错误时出现 ArrayIndexOutOfBounds 异常。

另一种方法是使用流:

Arrays.stream(cookies.split(";")).forEach(cookieStr -> map.put(cookieStr.split("=")[0], cookieStr.split("=")[1]));

正如 @WJS 在评论中提到的,你可以使用 map.putIfAbsent(key, value) 来代替 map.put(key, value),以防止覆盖值。但是在处理 cookies 时,可能希望用新值覆盖旧值。

英文:

You could use a loop to iterate over the key value pairs and put them into the map:

String[] cookieArr = cookies.split(&quot;;&quot;);
for(String cookieString : cookieArr){
  String[] pair = cookieString.split(&quot;=&quot;);
  if(pair.length &lt; 2){
    continue;
  }
  map.put(pair[0], pair[1]);
}

The if is only there to prevent ArrayIndexOutOfBounds expcetions if cookie string is malformed

an alternativ would be using a stream:

Arrays.stream(cookies.split(&quot;;&quot;)).forEach(cookieStr -&gt; map.put(cookieStr.split(&quot;=&quot;)[0], cookieStr.split(&quot;=&quot;)[1]));

As mentioned by @WJS in the comment, you could use map.putIfAbsent(key, vlaue) instead of map.put(key, value) to prevent overriding of values. But in case of cookies it could be a desired behavior to overwrite the old value with the new.

答案2

得分: 3

你可以这样做。它假定你的格式是一致的。

  • 首先将每个k/v对分割在"";""上。
  • 然后在""=""上分割成键和值。
  • 然后添加到映射中。
  • 如果出现重复的键,首次遇到的键会优先(如果你想要重复键的最新值,则使用(a, b)-&gt; b作为合并lambda表达式)。
String cookies = "i=lol;haha=noice;df3=ddtb";
Map<String, String> map = Arrays.stream(cookies.split(";"))
		.map(str -> str.split("=")).collect(Collectors
				.toMap(a -> a[0], a->a[1], (a, b) -> a));
map.entrySet().forEach(System.out::println);

输出:

df3=ddtb
haha=noice
i=lol
英文:

You could do it like this. It presumes your format is consistent.

  • first splits each k/v pair on ";"
  • the splits on "=" into key and value.
  • and adds to map.
  • if duplicate keys show up, the first one encountered takes precedence (if you want the latest value for a duplicate key then use (a, b)-&gt; b as the merge lambda.)
String cookies = &quot;i=lol;haha=noice;df3=ddtb&quot;;
Map&lt;String, String&gt; map = Arrays.stream(cookies.split(&quot;;&quot;))
		.map(str -&gt; str.split(&quot;=&quot;)).collect(Collectors
				.toMap(a -&gt; a[0], a-&gt;a[1], (a, b) -&gt; a));
map.entrySet().forEach(System.out::println);

Prints

df3=ddtb
haha=noice
i=lol


</details>



huangapple
  • 本文由 发表于 2020年10月19日 22:09:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/64429111.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定