DEV Community

Surhid Amatya
Surhid Amatya

Posted on

joinToString() Kotlin function to get comma separated strings

Recently I had to display a series of strings as a comma-separated value in a text view. I was going to do it as I had done it in java but I did some google and tried to look into Kotlin's way. Over the observing Kotlin code and example, I adopted a practice which made me utilize Kotlin at it's best- Each time you have to iterate a list for gathering data, consider searching for a Kotlin function or an operator that doesn't require you to write a for loop.

This practice led me to use the joinToString() Kotlin method to reduce loop usage to create a list of comma-separated "string" values from an Array.
Here I am going to display how I used to do and how Kotlin made the task easier

Java Syntax:

List<String> serialNumbers = new ArrayList();
for (int i=0; i< serialNumbers.size(); i++) {
VehicleSerialNumber vehicleSerialNumber = serialNumbers.get(i);
StringBuilder separatedSerialNumber = new StringBuilder();
separatedSerialNumber.append("\'"+vehicleSerialNumber.nameOfStringVariable +"\'");
if (i != listOfStringColumn.size() -1 ) {
separatedSerialNumber.append(", ");
Enter fullscreen mode Exit fullscreen mode

Kotlin Code:

val separatedSerialNumber = serialNumbers.joinToString { it }
Output: a, v, b, d, g
Enter fullscreen mode Exit fullscreen mode

… and that's it! reduced 9 lines of code to 1 line. No for loop, no using unnecessary conditional code (to remove last appended ',').

Kotlin joinToString() Function :
The joinToString() function is used to convert an array or a list to a string that is separated from the mentioned separator.
Comma with a space (, ) is the default separator used, if we need to use a different separator, we can mention it like so:
Let's use "-" as a separator

val separatedSerialNumber = serialNumbers.joinToString (separator = "-") {it}
Output: a-v-c-d-g
Enter fullscreen mode Exit fullscreen mode

Keep coding. Keep helping. Happy coding!!!!

Top comments (0)