0

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>();
sanjay m
  • 63
  • 1
  • 16
  • 6
    "*I have a method with return type as string below*" - This is not a `String`, it's a `String[]` (or `Collection`). To convert a `String[]` in a `Set`, we can use [`Set.of(...)`](https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/Set.html#of(E...)). – Turing85 Sep 20 '20 at 08:31
  • Does this answer your question? [Java: How to convert String\[\] to List or Set](https://stackoverflow.com/questions/11986593/java-how-to-convert-string-to-list-or-set) – Svirin Sep 20 '20 at 08:57
  • It is a string set coming from AWS DynamoDB i am retrieving whole string set as a string only – sanjay m Sep 20 '20 at 09:30
  • my method return type is string – sanjay m Sep 20 '20 at 09:34

2 Answers2

2

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));
Niyas
  • 229
  • 1
  • 7
1

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());
pirho
  • 11,565
  • 12
  • 43
  • 70