I have been in the software development industry since 2010, working on enterprise product development using ADF. I am usually keen on learning about software design and emerging technologies. You can find me hanging around in the JavaRanch Forums where I am one of the moderators. Apart from Java, I am fascinated by the ease of use and simplicity of Ruby and Rails. Mohamed is a DZone MVB and is not an employee of DZone and has posted 58 posts at DZone. You can read more from them at their website. View Full User Profile

Converting a List into Comma Separated Value String in Java

05.13.2013
| 22130 views |
  • submit to reddit

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

he 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 aCollector 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.



Published at DZone with permission of Mohamed Sanaulla, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Felix Martin replied on Mon, 2013/05/13 - 6:31am

Well, while we waiting for java 8 to be released we can use the following clean and neat joinToString function:


public static String joinToString(Collection<?> collection, CharSequence separator) {

	if (collection.isEmpty()) {
		return "";
	} else {
		StringBuilder sepValueBuilder = new StringBuilder();

		for (Object obj : collection) {
			//Append the valuen and the separator even if it's the las element
			sepValueBuilder.append(obj).append(separator);
		}
		//Remove the last separator
		sepValueBuilder.setLength(sepValueBuilder.length() - separator.length());

		return sepValueBuilder.toString();

	}
}

Moe Lavigne replied on Mon, 2013/05/13 - 2:17pm

 Or you can put this code in a general purpose utility class (in my case PMU)

  public static String convertArrayIntoCSV(Object[] aValues) {

    StringBuilder sbCSV = new StringBuilder();
    for (Object sValue : aValues) {

      sbCSV.append(",").append(sValue.toString());
    }

    //Substring removes leading "," if one exists;
    return sbCSV.substring(Math.min(1, sbCSV.length())).toString();
  }

and your code looks like this...

String sCSV = PMU.convertArrayIntoCSV(String[] ???) OR

String sCSV = PMU.convertArrayIntoCSV(Integer[] ???) etc.

Gagandeep Singh replied on Mon, 2013/05/13 - 2:23pm

view sourceprint?1.List<Integer> numbers = Arrays.asList(1,2,3,4,5,6,7);2.System.out.println(numbers.toString().substring(1,numbers.toString().length()-1));
The above uses the already existing implementation of toString and just removes the braces to achieve it is simple for , as delimiter.

Mohamed Sanaulla replied on Tue, 2013/05/14 - 1:50am in response to: Gagandeep Singh

I never thought of this. Really cool. Thanks for sharing it! 

Mohamed Sanaulla replied on Tue, 2013/05/14 - 1:52am in response to: Moe Lavigne

Agree that we can put it in an Util. 

I got another approach using Google Guava as a comment on my blog. 

Lukas Eder replied on Wed, 2013/05/15 - 10:04am

Even better, use method references:

.map(String::valueOf)

Instead of

.map(number -> String.valueOf(number))

Mohamed Sanaulla replied on Wed, 2013/05/15 - 11:48am in response to: Lukas Eder

Cool! May be I should add it to my post. Can I? 

Alvin Lim replied on Thu, 2013/05/16 - 12:38am

If your main concern is code verbosity and you don't really care about implementation, you could simply include Apache Commons Lang.

import org.apache.commons.lang.StringUtils;


String csv = StringUtils.join(listOfIntegers,",");

Lukas Eder replied on Thu, 2013/05/16 - 1:59am in response to: Mohamed Sanaulla

Of course, go ahead. More authoritative info can be cited from Brian Goetz's public documentation about the state of the lambda:

Lund Wolfe replied on Sun, 2013/05/19 - 12:21am in response to: Alvin Lim

+1 for quality and readability

// assuming a List of String, you can go both ways
List<String> listOfString = Arrays.asList(StringUtils.split(csv, ","));

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.