如何在Java中将String转换为字符串集合。

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

How to convert String to string set in java

问题

我有一个返回类型为字符串的方法以下是获取的字符串我应该如何将这个字符串转换为 "Set<String>"以便我可以迭代访问字符串集合

    ["date:@value2", "lineofbusiness:@value3", "pnrno:@value1", "reason:@value4"]

如果我尝试使用 String[] 进行分割结果不是预期的我必须获得像 **date:@value2** 这样的单独值并将其拆分以完成我其余的逻辑

如何将上述字符串转换为下面的字符串集合

    Set<String> columnmapping = new HashSet<String>();
英文:

I have a method with return type as string below is the string which is getting retrieved how should in convert this string to set<String>so that i can iterate through the String set.

[&quot;date:@value2&quot;,&quot;lineofbusiness:@value3&quot;,&quot;pnrno:@value1&quot;,&quot;reason:@value4&quot;]

If i try to split using String[] the result is not expected i have to get these individual values like date:@value2 and have to split this to complete the rest of my logic.

How to convert the above string to below string set

Set&lt;String&gt; columnmapping = new HashSet&lt;String&gt;();

答案1

得分: 2

我使用Apache Commons进行字符串操作。以下代码有所帮助。

String substringBetween = StringUtils.substringBetween(str, "[", "]").replaceAll("\"", ""); // 去除括号和引号
String[] csv = StringUtils.split(substringBetween, ","); // 逗号分割
Set<String> columnmapping = new HashSet<String>(Arrays.asList(csv));
英文:

I use Apache Commons for string manipulation. Following code helps.

String substringBetween = StringUtils.substringBetween(str, &quot;[&quot;, &quot;]&quot;).replaceAll(&quot;\&quot;&quot;, &quot;&quot;); // get rid of bracket and quotes
String[] csv = StringUtils.split(substringBetween,&quot;,&quot;); // split by comma
Set&lt;String&gt; columnmapping  = new HashSet&lt;String&gt;(Arrays.asList(csv));

答案2

得分: 1

除了被接受的答案之外,还有许多选项可以使用标准的 Java Streams(假设 Java >= 8)在 "一行代码" 中完成,而且不需要任何外部依赖。例如:

String s =
"[\\"date:@value2\\",\\"lineofbusiness:@value3\\",\\"pnrno:@value1\\",\\"reason:@value4\\"]";
Set<String> strings = Arrays.asList(s.split(",")).stream()
                            .map(s -> s.replaceAll("[\\[\\]]", ""))
                            .collect(Collectors.toSet());
英文:

In addition to the accepted answer there are many options to make it in "a single line" with standards Java Streams (assuming Java >= 8) and without any external dependencies, for example:

String s =
&quot;[\&quot;date:@value2\&quot;,\&quot;lineofbusiness:@value3\&quot;,\&quot;pnrno:@value1\&quot;,\&quot;reason:@value4\&quot;]&quot;;
Set&lt;String&gt; strings = Arrays.asList(s.split(&quot;,&quot;)).stream()
                            .map(s -&gt; s.replaceAll(&quot;[\\[\\]]&quot;, &quot;&quot;))
                            .collect(Collectors.toSet());

huangapple
  • 本文由 发表于 2020年9月20日 16:27:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/63976986.html
匿名

发表评论

匿名网友

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

确定