<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>brute force &#8211; CodePills.com</title>
	<atom:link href="https://codepills.com/tag/brute-force/feed/" rel="self" type="application/rss+xml" />
	<link>https://codepills.com</link>
	<description>Helping you make a better code</description>
	<lastBuildDate>Wed, 26 Jan 2022 14:28:42 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	
	<item>
		<title>How to join List String elements with a comma</title>
		<link>https://codepills.com/how-to-join-list-string-elements-with-a-comma/</link>
					<comments>https://codepills.com/how-to-join-list-string-elements-with-a-comma/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Sat, 01 Jan 2022 14:09:21 +0000</pubDate>
				<category><![CDATA[Language basics]]></category>
		<category><![CDATA[brute force]]></category>
		<category><![CDATA[Java 8]]></category>
		<guid isPermaLink="false">https://codepills.com/?p=1277</guid>

					<description><![CDATA[In this article, we will see three different ways to print string elements of the list into one coherent text. <a href="https://codepills.com/how-to-join-list-string-elements-with-a-comma/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>This article will show three different ways to print string elements of the list into one coherent text.</p>
<p><span id="more-1277"></span></p>
<h2>Introduction</h2>
<p>A software developer encounters the trivial task of joining string elements in the list from time to time into one coherent text. Reasons vary widely &#8211; from printing elements to logs to showing the text to the user. But be sure that the solution for this problem should be straightforward when you want to use the Java programming language the most effectively.</p>
<p>We will use a list of random US states codes such as  TX, WA, NY etc., for demonstration in our showcases.</p>
<p>First of all, let me show you the proper way to utilize the Java language most effectively. These solutions will require to use of at least version Java 8.</p>
<h2>String build-in join method</h2>
<p>Java 8 implemented to core String class, in a same way as many other programming languages, <code>join()</code> method. <code>join()</code> method has two arguments:</p>
<ul>
<li>The first argument is called <b>separator</b>. Separator is single character or sequence of characters with which elements should be joined together.</li>
<li>The second argument is the Java&#8217;s object implementing the List interface from which the elements will be taken and joined.</li>
</ul>
<p>Be noted that a separator can be a single character or sequence of characters. We will connect our US state codes on the sequence of characters: space + comma + space. You can use only a comma to get a more concise text.</p>
<pre><code class="language-java">package com.codepills;

import java.util.Arrays;
import java.util.List;

public class JoiningStatesWithJoinMethod {

    public static void main(String[] args) {
        List<String> states = Arrays.asList("TX", "WA", "NY", "AZ", "MI", "AL", "CA");
        String text = String.join(" , ", states);
        System.out.println(text);
    }

}</code></pre>
<p><b>Output</b></p>
<pre><code class="language-java">TX , WA , NY , AZ , MI , AL , CA</code></pre>
<h2>Joining String elements in Java Stream</h2>
<p>Another way to join string elements and create a single line of text is to stream through all the list elements and join them on a collection of characters or sequences of characters. Unfortunately, this solution also requires using at least the Java 8 version since handling and collecting streams is a significant release feature of Java 8. Let&#8217;s use Collector&#8217;s <code>joining()</code> static method with single argument &#8211; separator.</p>
<pre><code class="language-java">package com.codepills;

import java.util.Arrays;
import java.util.List;

public class JoiningStatesWithStreamCollection {

    public static void main(String[] args) {
        List<String> states = Arrays.asList("TX", "WA", "NY", "AZ", "MI", "AL", "CA");
        String text = states.stream().collect(Collectors.joining(","));
        System.out.println(text);
    }

}</code></pre>
<p><b>Output</b></p>
<pre><code class="language-java">TX , WA , NY , AZ , MI , AL , CA</code></pre>
<h2>Brute force</h2>
<p>The last way to join strings together is to use simply brute force. Using brute force is the last option as it creates more code than necessary. Especially for newer versions of Java, it is recommended to use String&#8217;s build-in <code>join()</code> method. Therefore brute-force is more or less an option for legacy code, code written in Java 7 and less.</p>
<pre><code class="language-java">package com.codepills;

import java.util.Arrays;
import java.util.List;

public class JoiningStatesWithBruteForce {

    public static void main(String[] args) {
        System.out.println(customJoin(",", Arrays.asList("TX", "WA", "NY", "AZ", "MI", "AL", "CA")));
        System.out.println(customJoin(",", Arrays.asList("TX")));
        System.out.println(customJoin(",", Arrays.asList("")));
        System.out.println(customJoin(",", null));
    }

    private static String customJoin(String separator, List<String> input) {

        if (input == null || input.size() <= 0) return "";

        StringBuilder stringBuilder = new StringBuilder();

        for (int i = 0; i < input.size(); i++) {
            stringBuilder.append(input.get(i));
            // Do not print separator for the last element
            if (i != input.size() - 1) {
                stringBuilder.append(separator);
            }
        }

        return stringBuilder.toString();
    }

}</code></pre>
<p><b>Output</b></p>
<pre><code class="language-java">TX , WA , NY , AZ , MI , AL , CA
TX
 // empty
</code></pre>
<p>We placed all possible options for input to <code>main()</code> method in order to test our <code>customJoin()</code> method properly.</p>
<p>Eventually, you can see we are using more custom code than is necessary. All this custom functionality can be replaced by single line in case of String's <code>join()</code> method. Therefore use this custom solution only when it does make sense.</p>
<h2>Conclusion</h2>
<p>This article has shown three different ways to print string elements of the list into one coherent test.</p>
<p>Did you find concatenating easy? Do you have your trick or know another way <u>how to join list elements</u>? Let us know in the comments below the article. We would like to hear your ideas and stories.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/how-to-join-list-string-elements-with-a-comma/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
