简体   繁体   English

Java将字符串数组转换为列表

[英]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. 我想从中获取List<String> ,问题是有时它可以是单个值,有时可以是多个值,以逗号分隔。

I tried to use Arrays.asList(multipleArray) but it didn't work. 我尝试使用Arrays.asList(multipleArray)但是没有用。

Any suggestions? 有什么建议么?

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

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. 如Bas.E所述,我的解决方案根据您的示例对数据进行处理。

  1. Remove [ and ] from the beginning and ending using substring . 使用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); 

From asList(T...) It should be like: asList(T ...)它应该像:

List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");

Now in your question you have to create array then pass it to Arrays.asList 现在在您的问题中,您必须创建数组,然后将其传递给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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM