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

<br />
package com.programtalk.java8.flattenlist;</p>
<p>import java.util.Arrays;<br />
import java.util.List;</p>
<p>public class FlattenList {</p>
<p>	public static void main(String[] args) {<br />
		List&lt;String&gt; stringList = Arrays.asList(&quot;Please&quot;, &quot;concatenate&quot;,&quot;me&quot;);<br />
		String concatenatedStrings = String.join(&quot;, &quot;, stringList);<br />
		System.out.println(concatenatedStrings);<br />
	}<br />
}</p>
<p>

output

</p>
<p>Please, concatenate, me</p>
<p>

Using org.apache.commons.lang3.StringUtils

</p>
<p>package com.programtalk.beginner.tutorial;</p>
<p>import java.util.Arrays;<br />
import java.util.List;</p>
<p>import org.apache.commons.lang3.StringUtils;</p>
<p>public class FlattenList {</p>
<p>	public static void main(String[] args) {<br />
		List&lt;String&gt; stringList = Arrays.asList(&quot;Please&quot;, &quot;concatenate&quot;,&quot;me&quot;);<br />
		String concatenatedStrings = StringUtils.join(stringList,&quot;, &quot;);<br />
		System.out.println(concatenatedStrings);<br />
	}<br />
}</p>
<p>

output :

</p>
<p>Please, concatenate, me</p>
<p>

Using loop

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

<br />
package com.programtalk.beginner.tutorial;</p>
<p>import java.util.Arrays;<br />
import java.util.List;</p>
<p>public class FlattenListUsingLoop {</p>
<p>	private static String separator =&quot;, &quot;;</p>
<p>	public static void main(String[] args) {<br />
		List&lt;String&gt; stringList = Arrays.asList(&quot;Please&quot;, &quot;concatenate&quot;,&quot;me&quot;);<br />
		StringBuilder stringBuilder = new StringBuilder();<br />
	    String sep = &quot;&quot;;<br />
	    for(String s: stringList) {<br />
	        stringBuilder.append(sep);<br />
	        stringBuilder.append(s);<br />
	        sep = separator;<br />
	    }<br />
	    String concatenatedStrings =  stringBuilder.toString();<br />
		System.out.println(concatenatedStrings);<br />
	}<br />
}</p>
<p>

output

</p>
<p>Please, concatenate, me</p>
<p>

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

One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.