List:["a","b","c"]
转换后:a,b,c
1、String.join
java
// 1. 创建一个List集合 数量不可变
List<String> list = List.of("a", "b", "c");
//list = [a, b, c]
System.out.println("list = " + list);
String join = String.join(",", list);
//join = a,b,c
System.out.println("join = " + join);
2、谷歌工具类 Joiner
import com.google.common.base.Joiner;
java
// 1. 创建一个List集合 数量不可变
List<String> list = List.of("a", "b", "c");
//list = [a, b, c]
System.out.println("list = " + list);
String join = Joiner.on(",").join(list);
//join = a,b,c
System.out.println("join = " + join);
3、forEach
java
// 1. 创建一个List集合 数量不可变
List<String> list = List.of("a", "b", "c");
//list = [a, b, c]
System.out.println("list = " + list);
StringBuffer join = new StringBuffer();
//和list.forEach没啥区别
//list.stream().forEach(s -> join.append(s).append(","));
//可以并行处理
//list.parallelStream().forEach(s -> join.append(s).append(","));
list.forEach(s -> join.append(s).append(","));
//join = a,b,c
System.out.println("join = " + join);
4、list.stream
java
// 1. 创建一个List集合 数量不可变
List<String> list = List.of("a", "b", "c");
//list = [a, b, c]
System.out.println("list = " + list);
//map(String::toString)将流中的每个元素转换为字符串
String join = list.stream().map(String::toString).collect(Collectors.joining(","));
//map(String::valueOf)也将流中的每个元素转换为字符串,但对于非字符串类型的元素,会先调用toString()方法转换为字符串
String join1 = list.stream().map(String::valueOf).collect(Collectors.joining(","));
//join = a,b,c
System.out.println("join = " + join);
5、apache 工具类
import org.apache.tomcat.util.buf.StringUtils;
java
// 1. 创建一个List集合 数量不可变
List<String> list = List.of("a", "b", "c");
//list = [a, b, c]
System.out.println("list = " + list);
String join = StringUtils.join(list, ',');
//join = a,b,c
System.out.println("join = " + join);
import org.apache.commons.lang.StringUtils;
// 1. 创建一个List集合 数量不可变
List<String> list = List.of("a", "b", "c");
//list = [a, b, c]
System.out.println("list = " + list);
//String join = StringUtils.join(list, ","); 单引号,双引号都可以
String join = StringUtils.join(list, ',');
//join = a,b,c
System.out.println("join = " + join);
6、for 循环
java
StringBuffer join = new StringBuffer();
// 1. 创建一个List集合 数量不可变
List<String> list = List.of("a", "b", "c");
//list = [a, b, c]
System.out.println("list = " + list);
for (int i = 0; i < list.size(); i++) {
join.append(list.get(i));
if (i != list.size() - 1) {
join.append(",");
}
}
//join = a,b,c
System.out.println("join = " + join);