Java8 – Convert List to comma separated String in java

Converting List<String> to comma separated string in java8 is very simple and straight forward, with String join We simply can write String.join(..), pass a delimiter and an Iterable and the new StringJoiner will do the rest. If we are  working with a stream we can write it using Collectors.

Here is the CSVUtil class and couple of tests.

package com.jminded.java8;
 
import java.util.List;
import static java.util.stream.Collectors.joining;
 
/**
 * https://jminded.com
 * 
 * @author Umashankar
 *
 */
public class CSVUtil {
 
	private static final String SEPARATOR = ",";
	/**
	 * 
	 * @param listToConvert
	 * @return
	 */
	public static String toCsv(List<String> listToConvert) {
		return String.join(SEPARATOR, listToConvert);
	}
	/**
	 * 
	 * @param listToConvert
	 * @return
	 */
	public static String toCsvStream(List<String> listToConvert) {
		return listToConvert.stream().collect(joining(SEPARATOR));
	}
}
package com.jminded.java8;
 
import java.util.Arrays;
import java.util.List;
 
import org.junit.Test;
import static org.junit.Assert.assertEquals;
 
/**
 * https://jminded.com
 * 
 * @author Umashankar
 *
 */
public class CSVUtilTest {
 
	@Test
	public void toCsv_csvFromListOfString() {
		List<String> securities = Arrays.asList("Stock", "Future", "Option", "Forex", "ETF");
		String expected = "Stock,Future,Option,Forex,ETF";
		assertEquals(expected, CSVUtil.toCsv(securities));
	}
 
	@Test
	public void toCsvStream_csvFromListOfString() {
		List<String> securities = Arrays.asList("Stock", "Future", "Option", "Forex", "ETF");
		String expected = "Stock,Future,Option,Forex,ETF";
		assertEquals(expected, CSVUtil.toCsvStream(securities));
	}
}

Leave a Comment