Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert ArrayList to String

Tags:

java

list

I have an ArrayList and I need to convert it to one String.

Each value in the String will be inside mark and will be separated by comma something like this:

ArrayList list = [a,b,c]

String s = " ’a’,’b’,’c’ ";

I am looking for efficient solution .

like image 606
angus Avatar asked Feb 19 '23 18:02

angus


1 Answers

You can follow these steps: -

  • Create an empty StringBuilder instance

    StringBuilder builder = new StringBuilder();
    
  • Iterate over your list

  • For each element, append the representation of each element to your StringBuilder instance

    builder.append("'").append(eachElement).append("', ");
    
  • Now, since there would be a last comma left, you need to remove that. You can use StringBuilder.replace() to remove the last character.

You can take a look at documentation of StringBuilder to know more about various methods you can use.

like image 177
Rohit Jain Avatar answered Feb 21 '23 07:02

Rohit Jain