https://kotlinlang.org logo
#codereview
Title
# codereview
j

jean

11/13/2020, 7:44 AM
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

bezrukov

11/13/2020, 7:51 AM
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

Liudvikas Sablauskas

11/13/2020, 7:53 AM
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

jean

11/13/2020, 7:54 AM
nice 🙂 thanks guys!
a

aleksey.tomin

11/13/2020, 7:56 AM
or
Copy code
private fun cookieStringToMap(string: String) =
    string.split(";")
        .map { it.split("=") }
        .associate { it[0] to it[1] }
g

gildor

11/13/2020, 9:36 AM
it’s the same as Liubvikas code, but less efficient, it requires additional intermediate list
☝️ 1
c

christophsturm

11/13/2020, 10:52 AM
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
4 Views