wiryadev
wiryadev

Reputation: 1491

Convert String to Integer List in Kotlin

I want to make function for typeconverter room. The original data is in List and i store it as String in database.

My code and the output is like this:

fun main() {
    val genreIds = listOf(28, 80)
    val stringFromList = fromList(genreIds)
    val stringToList = toList(stringFromList)
    
    println(genreIds) // output: [28, 80]
    println(stringFromList) // output: [28, 80]
    println(stringToList) // output: [91, 50, 56, 44, 32, 56, 48, 93]
}

fun fromList(genreIds: List<Int>): String = genreIds.toString()

fun toList(genreIdString: String): List<Int> {
    return genreIdString.map { it.toInt() }
}

I did try to use split(",") but it always give me error because of the "[" and "]". I want the output of toList function is [28, 80] too. Thanks for help.

Upvotes: 0

Views: 2218

Answers (3)

FWDekker
FWDekker

Reputation: 2879

Use the removeSurrounding method to remove delimiters:

fun toList(genreIdString: String): List<Int> =
    genreIdString
        .removeSurrounding("[", "]")
        .split(", ")
        .map { it.toInt() }

I think this approach is better than using substring because it more clearly conveys your intent.

Upvotes: 1

Konstantin Raspopov
Konstantin Raspopov

Reputation: 1615

It doesn't seem to be a good idea to parse the input manually. I propose to use Kotlin Serialization library for this purpose.

Using it you can write as simple as:

import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json

fun main() {
    val list = listOf(1, 2, 3)
    val str = Json.encodeToString(list)
    println(str) // "[1,2,3]"
    val list2: List<Int> = Json.decodeFromString(str)
    println(list2) // [1, 2, 3]
}

Upvotes: 1

Aplet123
Aplet123

Reputation: 35512

You can use substring to remove the first and last character:

fun toList(genreIdString: String): List<Int> =
    genreIdString
        .substring(1, genreIdString.length - 1)
        .split(", ")
        .map { it.toInt() }

Upvotes: 2

Related Questions