Java8将List转变为逗号分隔的字符串import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Test {
/**
* 将List转变为逗号分隔的字符串
*
* @param args
*/
public static void main(String[] args) {
/**
* JDK8
*/
List<String> cities = Arrays.asList("Milan", "London", "New York", "San Francisco");
String citiesCommaSeparated = String.join(",", cities);
字符串截取逗号System.out.println(citiesCommaSeparated);
citiesCommaSeparated = cities.stream().collect(Collectors.joining(","));
System.out.println(citiesCommaSeparated);
/**
* JDK8以前版本
*/
String SEPARATOR = ",";
StringBuilder csvBuilder = new StringBuilder();
for (String city : cities) {
csvBuilder.append(city);
csvBuilder.append(SEPARATOR);
}
String csv = String();
csv = csv.substring(0, csv.length() - SEPARATOR.length());
System.out.println(csv);
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论