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 = csvBuilder.toString();
		csv = csv.substring(0, csv.length() - SEPARATOR.length());
		System.out.println(csv);
	}

}

posted on 2019-03-05 18:46  疯狂的小萝卜头  阅读(2158)  评论(0编辑  收藏  举报