Java List转换为字符串的几种方法

时间:2021-03-31 14:52:51

Java List转换为字符串的几种方法

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List; // 参考:https://blog.csdn.net/vasilis_1/article/details/75499087
public class ListToStringTest { public static String listToString1(List list, char separator) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < list.size(); i++) {
sb.append(list.get(i)).append(separator);
}
return list.isEmpty() ? "" : sb.toString().substring(0, sb.toString().length() - 1);
} public static String listToString2(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();
} public static String listToString3(List list, char separator) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < list.size(); i++) {
sb.append(list.get(i));
if (i < list.size() - 1) {
sb.append(separator);
}
}
return sb.toString();
} // 总结:方法五在实际应用中最多,因为它已经被封装好了,速度也很快
public static String listToString4(List list, char separator) {
return StringUtils.join(list.toArray(), separator);
} public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
System.out.println(ListToStringTest.listToString1(list, '+'));
System.out.println(ListToStringTest.listToString2(list, '-'));
System.out.println(ListToStringTest.listToString3(list, '*'));
System.out.println(ListToStringTest.listToString4(list, '/'));
} }

参考:

Java List转换为字符串的几种方法

参考:java List转换为字符串的几种方法