我有一个 ArrayList
,我需要将它转换为一个字符串。
每个值都将被放在引号内,并以逗号分隔,就像这样:
ArrayList list = [a,b,c]
String s = " ’a’,’b’,’c’ ";
我正在寻找高效的解决方案。
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.
StringBuilder
文档,了解更多可用的方法。append("'" + eachElement + "', ")
,那么使用 StringBuilder
有什么意义呢? - adarshr也许这里有点过度,但是通过 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));
}
}
使用Apache org.apache.commons.lang3.StringUtils库中的StringUtils。
StringUtils.join(list, ", ");
或者
String s = (!list.isEmpty())? "'" + StringUtils.join(list , "', '")+ "'":null;