英文:
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.
["date:@value2","lineofbusiness:@value3","pnrno:@value1","reason:@value4"]
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<String> columnmapping = new HashSet<String>();
答案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, "[", "]").replaceAll("\"", ""); // get rid of bracket and quotes
String[] csv = StringUtils.split(substringBetween,","); // split by comma
Set<String> columnmapping = new HashSet<String>(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 =
"[\"date:@value2\",\"lineofbusiness:@value3\",\"pnrno:@value1\",\"reason:@value4\"]";
Set<String> strings = Arrays.asList(s.split(",")).stream()
.map(s -> s.replaceAll("[\\[\\]]", ""))
.collect(Collectors.toSet());
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论