Any better way than this to transform a string to ...
# codereview
j
Any better way than this to transform a string to a map?
Copy code
private fun cookieStringToMap(string: String): Map<String, String> {
    val map = mutableMapOf<String, String>()
    string.split(";").forEach { entry ->
        val parts = entry.split("=")
        map[parts[0]] = parts[1]
    }
        
    return map
}
b
how about this:
Copy code
private fun cookieStringToMap(string: String): Map<String, String> {
    return string.split(";").map { entry ->
        val (key, value) = entry.split("=")
        key to value
    }.toMap()
}
l
Copy code
private fun cookieStringToMap(string: String) =
    string.split(";").associate { entry ->
        val (key, value) = entry.split("=");
        key to value
    }
associate
does the
toMap
part for you basically
1
j
nice 🙂 thanks guys!
a
or
Copy code
private fun cookieStringToMap(string: String) =
    string.split(";")
        .map { it.split("=") }
        .associate { it[0] to it[1] }
g
it’s the same as Liubvikas code, but less efficient, it requires additional intermediate list
☝️ 1
c
Copy code
"a=b;c=d".splitToSequence(";")
        .map { it.split("=") }
        .associate { it[0] to it[1] }
with a sequence you have both readability and performance
💯 4
👍 6