Converting a List into comma separated value string in Java

We all have at least once in our coding life time done this: “Concatenate the elements of a List into a comma separated string”. And each time we have spent some time figuring out how to do it or sometimes we copy the code from a previous implementation. Lets see how we can implement this scenario:

public class ListToCommaValues {

  public static void main(String[] args) {
  
    //List of numbers we want to concatenate
    List<Integer> numbers = Arrays.asList(1,2,3,4,5,6,7);

    //The string builder used to construct the string
    StringBuilder commaSepValueBuilder = new StringBuilder();

    //Looping through the list
    for ( int i = 0; i< numbers.size(); i++){
      //append the value into the builder
      commaSepValueBuilder.append(numbers.get(i));
      
      //if the value is not the last element of the list
      //then append the comma(,) as well
      if ( i != numbers.size()-1){
        commaSepValueBuilder.append(", ");
      }
    }
    System.out.println(commaSepValueBuilder.toString());

  }

}

the output would be: 1, 2, 3, 4, 5, 6, 7. Its not rocket science, but just too much verbose and clumsy to write.

You all must be wondering the purpose of writing this article or taking up this scenario. At the Great Indian Developer Conference today Venkat Subramaniam was giving a talk on Design patterns in Modern JVM languages (Groovy, Scala) and mentioned about this scenario and also showed some code in Scala, Groovy and he also mentioned about Java 8. And bang I got an idea to blog about this and here is the same in front of you all.

Lets see how the same can be done in Java 8:

//Java 8 way to concatenate the list of numbers
public class ListToCommaValuesJava8 {

  public static void main(String[] args) {
  
    List<Integer> numbers = Arrays.asList(1,2,3,4,5,6,7);
    
    System.out.println(numbers.stream()
        .map(number -> String.valueOf(number))
        .collect(toStringJoiner(", ")));
  }
}

And the output again would be: 1, 2, 3, 4, 5, 6, 7. The above code is less verbose and much easier to read than the one shown in the beginning. If you are left wondering about stream(), collect() I would recommend you to read a similar and more detailed post using the same.

Let me explain the above single line of code:
map() – Takes in a lambda expression which accepts an argument and returns some value(this is an implementation of java.util.Function interface). In the example above the lambda expression accepts an integer and converts it into a string.

toStringJoiner() – It is a static method in Collectors class and returns a Collector which embeds the logic to use the elements of the stream and combine them into a new StringJoiner instance using the separator passed to the Collector.

StringJoiner– From the Javadoc: StringJoiner is used to construct a sequence of characters separated by an infix delimiter and optionally starting with a supplied prefix and ending with a supplied suffix. In the above example we are making use of the infix delimiter.

5 thoughts on “Converting a List into comma separated value string in Java”

  1. You’re looking for less verbose code to convert a List into a comma separated value string in Java? Lambda expressions are a powerful tool, but it can be done even easier: Use the guava library and you can simply write:

    String commaSeperated = Joiner.on(“, “).join(numbers);

    Reply

Leave a Reply

Discover more from Experiences Unlimited

Subscribe now to keep reading and get access to the full archive.

Continue reading