Home > Net >  Convert a String representation of a list to a List<String>
Convert a String representation of a list to a List<String>

Time:11-04

I have a string in the format: "[a, b, c]".

I would like to convert this to List such as: ["a", "b", "c"].

I am receiving this string from an API request.

My solution at the moment is:

String newString = "[a, b, c]".replaceAll("\\[|\\]| ", "");
List<String>  newList = Arrays.asList(newString.split(","));

Is there a better solution than this? Maybe using Jackson?

Thank you.

I have searched stack overflow and searching google for the answer. I am not sure if I a phrasing it correctly.

CodePudding user response:

Pattern.splitAsStream()

You can use the following regular expression "[^\\p{Alpha}] " that capture one or more non-alphabetic character to split the given string.

By using Pattern.splitAsStream() you can create a stream of substrings directly from the regex engine identical to the ones that can be produced via String.split but without allocating an intermediate array in memory.

Pattern p = Pattern.compile("[^\\p{Alpha}] ");
        
List<String> result = p.splitAsStream("[a, b, c]")
    .dropWhile(String::isEmpty) // the first element might be empty (linke with this sample data), if that's the case - we don't need it
    .toList();
    
System.out.println(result);

Output:

[a, b, c]

Parsing JSON

Maybe using Jackson?

You can use Jackson or any other tool for parsing JSON only if you're dialing with a valid JSON.

But string "[a, b, c]" is not a valid JSON. You can check it here.

The string below would be an example of a valid JSON-array:

String jsonStr = """
    ["a", "b", "c"]
""";

That's how it can be parsed using Jackson library:

ObjectMapper mapper = new ObjectMapper();
List<String> strings = mapper.readValue(jsonStr, new TypeReference<>() {});

System.out.println(strings);

Output:

[a, b, c]

CodePudding user response:

If you use the split() function on your original Array [a, b, c] passing the comma you will have ["a", "b", "c"] like in your example. I don't think the regular expression is necessary.

Please let me know if I am misunderstanding your question.

  • Related