Liad Livnat
Liad Livnat

Reputation: 7475

Java Convert string array to list

I have the following string and would like to convert it to string array

String singleArray = "[501]"
String multipleArray = "[1,501,634]"

I would like to get List<String> from that, the thing is sometimes it can be a single value and sometimes it can be multiple value seperate by comma.

I tried to use Arrays.asList(multipleArray) but it didn't work.

Any suggestions?

Upvotes: 3

Views: 4612

Answers (5)

Saif
Saif

Reputation: 7052

  1. Remove [ and ] from the beginning and ending using substring.
  2. split rest of the string according to the occurrence of ,.

    String[] arr = multipleArray.substring( 
                        1, multipleArray.length()-1).split(",");
    
  3. then use the array to make a list.

    List<String> list=Arrays.asList(arr);
    

Upvotes: 1

Scary Wombat
Scary Wombat

Reputation: 44854

How about

String arr [] = str.replace("[", "").replace ("]", "").split (",");

And then as per your knowledge, you can use the array to create a List using

Arrays.asList(arr);

Note

As noted by Bas.E, my solution works upon the data as per your example.

Upvotes: 7

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62874

  1. Get the substring between the first and the last character in order to get rid of the [ and ] characters.
  2. Split the resulting string by ,.

For example:

String input = "[1,501,634]";
String[] result = input.substring(1, input.length() - 1).split(",");
List<String> asList = Arrays.asList(result);

Upvotes: 9

MT0
MT0

Reputation: 168623

Remove the leading and trailing square brackets:

String removedBrackets = multipleArray.replaceAll( "^\\[|\\]$", "" );

or

String removedBrackets = multipleArray.substring( 1, multipleArray.length() - 1 );

Then split the string on the commas:

String[] arrayOfValues = removedBrackets.split( "," );

Then convert it to a list:

List<String> listOfValues = Arrays.asList( arrayOfValues );

Upvotes: 1

Uhla
Uhla

Reputation: 368

trim it from side brackets

array = array.substring(1,array.length()-1);

then split and convert to array

String[] arrayStringArray = array.split(",");

and if wanted, make it a List

List<String> arrayStringList = Arrays.asList(arrayStringArray);

Upvotes: 0

Related Questions