Convert ArrayList to String

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

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

 ArrayList list = [a,b,c] String s = " 'a','b','c' "; 

I am looking for an effective solution.

+4
source share
4 answers

You can perform the following actions: -

  • Create an empty StringBuilder instance

     StringBuilder builder = new StringBuilder(); 
  • Go through list

  • For each item, add a view of each item to an instance of StringBuilder

     builder.append("'").append(eachElement).append("', "); 
  • Now, since the last comma remains, you need to delete it. You can use StringBuilder.replace() to delete the last character.

You can look at the StringBuilder documentation to find out more about the various methods you can use.

+8
source

Take a look at StringBuilder and StringBuffer:

StringBuffer

StringBuilder

0
source

Maybe an overflow here, but a more functional approach via Guava :

 import com.google.common.base.Function; import com.google.common.base.Joiner; import com.google.common.collect.Collections2; import java.util.ArrayList; import java.util.Collection; import java.util.List; public class Main { public static void main(String ... args){ List<String> list = new ArrayList(){{add("a");add("b");add("c");}}; Collection<String> quotedList = Collections2.transform(list,new Function<String, String>() { @Override public String apply(String s) { return "'"+s+"'"; } }); System.out.println(Joiner.on(",").join(quotedList)); } } 
0
source

use the StringUtils library from Apache org.apache.commons.lang3.StringUtils;

  StringUtils.join(list, ", "); 

or

 String s = (!list.isEmpty())? "'" + StringUtils.join(list , "', '")+ "'":null; 
0
source

Source: https://habr.com/ru/post/1441148/


All Articles