How to join List String elements with a comma

This article will show three different ways to print string elements of the list into one coherent text.

Introduction

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 – 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.

We will use a list of random US states codes such as TX, WA, NY etc., for demonstration in our showcases.

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.

String build-in join method

Java 8 implemented to core String class, in a same way as many other programming languages, join() method. join() method has two arguments:

  • The first argument is called separator. Separator is single character or sequence of characters with which elements should be joined together.
  • The second argument is the Java’s object implementing the List interface from which the elements will be taken and joined.

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.

package com.codepills;

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

public class JoiningStatesWithJoinMethod {

    public static void main(String[] args) {
        List states = Arrays.asList("TX", "WA", "NY", "AZ", "MI", "AL", "CA");
        String text = String.join(" , ", states);
        System.out.println(text);
    }

}

Output

TX , WA , NY , AZ , MI , AL , CA

Joining String elements in Java Stream

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’s use Collector’s joining() static method with single argument – separator.

package com.codepills;

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

public class JoiningStatesWithStreamCollection {

    public static void main(String[] args) {
        List states = Arrays.asList("TX", "WA", "NY", "AZ", "MI", "AL", "CA");
        String text = states.stream().collect(Collectors.joining(","));
        System.out.println(text);
    }

}

Output

TX , WA , NY , AZ , MI , AL , CA

Brute force

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’s build-in join() method. Therefore brute-force is more or less an option for legacy code, code written in Java 7 and less.

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 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();
    }

}

Output

TX , WA , NY , AZ , MI , AL , CA
TX
 // empty

We placed all possible options for input to main() method in order to test our customJoin() method properly.

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 join() method. Therefore use this custom solution only when it does make sense.

Conclusion

This article has shown three different ways to print string elements of the list into one coherent test.

Did you find concatenating easy? Do you have your trick or know another way how to join list elements? Let us know in the comments below the article. We would like to hear your ideas and stories.

This entry was posted in Language basics and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published.

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