I have a method with return type as string below is the string which is getting retrieved how should in convert this string to setso 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>();
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));
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());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.