Yet Another Cleaner Way To Construct CSV String in Java

Accidentally found this util class while reading an ebook, and think it worth sharing since myself always found this a tedious code especially prefix and suffix the string.

We used to construct CSV string as below:

StringBuilder nameCsv = new StringBuilder();
nameCsv.append("Maria").append(",");
nameCsv.append("Ken").append(",");
nameCsv.append("Collin");
System.out.println(nameCsv.toString());
//OUTPUT: Maria,Ken,Collin

With new StringJoiner util in Java 1.8, we can do it in a cleaner way.

StringJoiner nameCsv = new StringJoiner(",");
nameCsv.add("Maria");
nameCsv.add("Ken");
nameCsv.add("Collin");
System.out.println(nameCsv.toString());
//OUTPUT: Maria,Ken,Collin

The constructor also allow us to prefix and suffix the string.

StringJoiner nameCsv = new StringJoiner(",", "{", "}");
nameCsv.add("Maria");
nameCsv.add("Ken");
nameCsv.add("Collin");
System.out.println(nameCsv.toString());
//OUTPUT: {Maria,Ken,Collin}

 

 

dicksonkho

 

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.