"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。List转变为逗号分隔的String(Java7和Java8分别实现)。" />

List转变为逗号分隔的String(Java7和Java8分别实现)

需求: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

【List转变为逗号分隔的String(Java7和Java8分别实现)】使用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

list和以逗号分割的String相互转换(guava)
import com.alibaba.fastjson.JSON; import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.common.base.Splitter; List list = Lists.newArrayList("a","b","c"," "); String s = Joiner.on(",").join(list); // 以逗号分割System.out.println(s); // a,b,c, Splitter split = Splitter.on(',').trimResults().omitEmptyStrings(); // 去前后空格&&去空stringList list1 = split.splitToList(s); System.out.println(JSON.toJSONString(list1)); // ["a","b","c"]

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

    推荐阅读