Flatten a list of Strings

In this tutorial we would see at various ways to concatenate a list of strings and insert a separator “,”  in between the concatenated strings.

Java 8

package com.programtalk.java8.flattenlist;

import java.util.Arrays;
import java.util.List;

public class FlattenList {

	public static void main(String[] args) {
		List<String> stringList = Arrays.asList("Please", "concatenate","me");
		String concatenatedStrings = String.join(", ", stringList);
		System.out.println(concatenatedStrings);
	}
}

output


Please, concatenate, me

Using org.apache.commons.lang3.StringUtils


package com.programtalk.beginner.tutorial;

import java.util.Arrays;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

public class FlattenList {

	public static void main(String[] args) {
		List<String> stringList = Arrays.asList("Please", "concatenate","me");
		String concatenatedStrings = StringUtils.join(stringList,", ");
		System.out.println(concatenatedStrings);
	}
}

output :


Please, concatenate, me

Using loop

See concatenation comparison for choosing a better way for string concatenation.

package com.programtalk.beginner.tutorial;

import java.util.Arrays;
import java.util.List;

public class FlattenListUsingLoop {

	private static String separator =", ";

	public static void main(String[] args) {
		List<String> stringList = Arrays.asList("Please", "concatenate","me");
		StringBuilder stringBuilder = new StringBuilder();
	    String sep = "";
	    for(String s: stringList) {
	        stringBuilder.append(sep);
	        stringBuilder.append(s);
	        sep = separator;
	    }
	    String concatenatedStrings =  stringBuilder.toString();   
		System.out.println(concatenatedStrings);
	}
}

output


Please, concatenate, me

Like this post? Don’t forget to share it!