List<String> cities = Arrays.asList("Milan", "London", "New York", "San Francisco"); String citiesCommaSeparated = String.join(",", cities); System.out.println(citiesCommaSeparated); //Output: Milan,London,New York,San Francisco
使用流的方式:
String citiesCommaSeparated = cities.stream() .collect(Collectors.joining(",")); System.out.println(citiesCommaSeparated);
使用流的方式,在连接之前操作字符串
String citiesCommaSeparated = cities.stream() .map(String::toUpperCase) .collect(Collectors.joining(",")); //Output: MILAN,LONDON,NEW YORK,SAN FRANCISCO