List to comma separated String of Java7 and Java8 implemented respectively
- 2021-09-24 22:24:22
- OfStack
Requirements: Arrays. asList ("AA", "BB")-- > "AA,BB"
In Java 8
Adopt stream mode
List<String> strList = Arrays.asList("AA", "BB", "CC");
String newStr = strList.stream().collect(Collectors.joining(","));
System.out.println("Output:" + newStr); // Output:AA,BB,CC
Using the String. join () function, passing a separator to the function to conform to an iterator, the StringJoiner object will help us do everything
String newStr = String.join(",", strList);
System.out.println("Output:" + newStr); // Output:AA,BB,CC
In Java 7
Implementation of Java 7
List<String> 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 and comma-split String interconversion (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<String> list = Lists.newArrayList("a","b","c"," ");
String s = Joiner.on(",").join(list); // Divided by commas
System.out.println(s); // a,b,c,
Splitter split = Splitter.on(',').trimResults().omitEmptyStrings(); // Remove the front and back spaces && Emptying string
List<String> list1 = split.splitToList(s);
System.out.println(JSON.toJSONString(list1)); // ["a","b","c"]