user3693762
user3693762

Reputation:

List<String> to string back to List in java

I have stored a java.util.List of Strings such as

[data1,data2,data3,data3,data7]

in a String.

How can I convert it back to a List of String, knowing that some values are just empty ?

Update: I am not able to convert implicitly. Getting error cannot cast string to string[]. Also tried converting to list. No success.

Update2: , cannot be used to split because the data also contains ,

Update 3: [/Simplify.do, action, temp,test,data] Data with , but without spaces is a single data.

Upvotes: 2

Views: 11596

Answers (2)

DejaVuSansMono
DejaVuSansMono

Reputation: 797

If I am understanding the questions correctly, and your data has a delimiter of a comma.

//if you have the brackets remaining and don't want them, remove them
data = data.replace("[","").replace("]","");


String data = "data1,data2,data3";
//You would put the second parameter as -1 if you want to keep any trailing blank values 
List<String> smapleData= Arrays.asList(data.split(",",-1));
//or if you don't want to keep trailing blanks
List<String> sampleDataTwo = Arrays.asList(data.split(","));

that would bring it back to a list of strings.

Upvotes: 10

sTg
sTg

Reputation: 4424

Use the below methodology for your query:

Initial Declaration:

  String myNewList=new String();
  String data = "data1,data2,data3";

Firstly split your values based on the comma which you can use as a delimiter

 myNewList=data.split(",");

And then pass it to a new list that will you give your desired result that is list of strings.

List<String> myList= Arrays.asList(myNewList);

Upvotes: 0

Related Questions