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?
[
and ]
characters. ,
. For example:
String input = "[1,501,634]";
String[] result = input.substring(1, input.length() - 1).split(",");
List<String> asList = Arrays.asList(result);
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.
[
and ]
from the beginning and ending using substring
. split rest of the string according to the occurrence of ,
.
String[] arr = multipleArray.substring( 1, multipleArray.length()-1).split(",");
then use the array to make a list.
List<String> list=Arrays.asList(arr);
From asList(T...) It should be like:
List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");
Now in your question you have to create array then pass it to Arrays.asList
String [] arr = multipleArray.replaceAll( "^\[|\]$", "").split( "," );
List<String> yourList = Arrays.asList(arr);
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 );
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);
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.