Kotlin program to convert one comma separated string to list

Introduction :

This tutorial will show you how to convert one comma separated strings to a list in Kotlin. Each word in the list will be one item of the list. For example, if the string is Hello, World, it will put both words in a list like [“Hello”, “World”].

We will use different ways to do this in Kotlin :

Using split-map :

The idea is to split the words in the string and put them back in a list. For that, we will use the following two functions :

  1. split(delimeter) and

  2. map()

  3. trim()

split returns a list of strings. It takes one delimeter and splits the string on that delimeter. If the string has comma separated words, the delimeter will be a comma_’,’_.

map() is used to process each words in that list of strings. We will use trim() to remove both trailing and leading spaces from the words and map will join them back to a list of all words.

Example program :

fun main() {
    val testStr1 = "Hello, World"
    val testStr2 = " Monday ,       Tuesday,    Wednesday   "

    val strList1 = testStr1.split(',').map{it.trim()}
    val strList2 = testStr2.split(',').map{it.trim()}

    println(strList1)
    println(strList2)
}

It will print :

[Hello, World]
[Monday, Tuesday, Wednesday]

Kotlin convert comma separated string list

Handling blank strings :

If we have blank strings, for example, let’s take a look at the below program :

fun main() {
    val testStr1 = "Hello,  ,   ,   , World"
    val testStr2 = " Monday ,  ,       Tuesday,    Wednesday   ,    ,   ,"

    val strList1 = testStr1.split(',').map{it.trim()}
    val strList2 = testStr2.split(',').map{it.trim()}

    println(strList1)
    println(strList2)
}

It will also adds these blanks in the list :

[Hello, , , , World]
[Monday, , Tuesday, Wednesday, , , ]

To avoid this, we can add one filter function to filter out only non-empty strings :

fun main() {
    val testStr1 = "Hello,  ,   ,   , World"
    val testStr2 = " Monday ,  ,       Tuesday,    Wednesday   ,    ,   ,"

    val strList1 = testStr1.split(',').map { it.trim() }.filter { it.isNotEmpty() }
    val strList2 = testStr2.split(',').map { it.trim() }.filter { it.isNotEmpty() }

    println(strList1)
    println(strList2)
}

It will print :

[Hello, World]
[Monday, Tuesday, Wednesday]

Similar tutorials :