项目中可能会遇见需要将 List 内容拼接成以逗号分隔的字符串的形式,现对实现方式做个小结
方法一:
代码语言:javascript复制public String listToString(List list, char separator) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < list.size(); i ) {
sb.append(list.get(i)).append(separator);
}
return sb.toString().substring(0,sb.toString().length()-1);
}
方法二
代码语言:javascript复制public String listToString(List list, char separator) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < list.size(); i ) {
if (i == list.size() - 1) {
sb.append(list.get(i));
} else {
sb.append(list.get(i));
sb.append(separator);
}
}
return sb.toString();}
方法三
代码语言:javascript复制public String listToString(List list, char separator) {
return org.apache.commons.lang.StringUtils.join(list.toArray(),separator);
}
参考地址:https://www.cnblogs.com/mr-wuxiansheng/p/7739463.html