1

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>();
4
  • 6
    "I have a method with return type as string below" - This is not a String, it's a String[] (or Collection<String>). To convert a String[] in a Set<String>, we can use Set.of(...). Commented Sep 20, 2020 at 8:31
  • Does this answer your question? Java: How to convert String[] to List or Set Commented Sep 20, 2020 at 8:57
  • It is a string set coming from AWS DynamoDB i am retrieving whole string set as a string only Commented Sep 20, 2020 at 9:30
  • my method return type is string Commented Sep 20, 2020 at 9:34

2 Answers 2

3

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));
Sign up to request clarification or add additional context in comments.

Comments

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());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.