Java8 List转变为逗号分隔的String

需求:Arrays.asList("AA", "BB") --> "AA,BB"


In Java 8

采用stream的方式

List strList = Arrays.asList("AA", "BB", "CC");
String newStr = strList.stream().collect(Collectors.joining(","));
System.out.println("Output:" + newStr); // Output:AA,BB,CC

使用String.join()函数,给函数传递一个分隔符合一个迭代器,StringJoiner对象会帮助我们完成所有的事情

String newStr = String.join(",", strList);
System.out.println("Output:" + newStr); // Output:AA,BB,CC

In Java 7

Java 7的实现方法

List strList = Arrays.asList("AA", "BB", "CC");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < strList.size(); i++) {
    if (i != 0) {
        sb.append(",");
    }
    sb.append(strList.get(i));
}
System.out.println("Output:" + sb.toString()); // Output:AA,BB,CC

你可能感兴趣的:(Java)