angus
angus

Reputation: 3320

Convert ArrayList to String

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 .

Upvotes: 4

Views: 8013

Answers (4)

Rohit Jain
Rohit Jain

Reputation: 213193

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.

Upvotes: 8

Marcin Wasiluk
Marcin Wasiluk

Reputation: 4864

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

    StringUtils.join(list, ", ");

or

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

Upvotes: 0

dimitrisli
dimitrisli

Reputation: 21381

Maybe an overkill here but providing a more functional approach through 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));
    }
}

Upvotes: 0

Bernd Elkemann
Bernd Elkemann

Reputation: 23550

Take a look at StringBuilder and StringBuffer:

StringBuffer

StringBuilder

Upvotes: 0

Related Questions