Home > Blockchain >  Kotlin: Printing all elements from a map with separators
Kotlin: Printing all elements from a map with separators

Time:04-19

I'm new to Kotlin. I'm curious what is the correct way to print all key:value pairs from a map with a separator. This is my solution, but somehow it doesn't feel right:

val m = mapOf("Juice" to 4.5, "Wine" to 8.0, "Soda" to 2.2)
val itr = m.iterator()
if(itr.hasNext()) {
    var drink = itr.next()
    print("${drink.key}: ${drink.value}")
}
while (itr.hasNext()) {
    var drink = itr.next()
    print(", ${drink.key}: ${drink.value}")
}

Output:

Juice: 4.5, Wine: 8.0, Soda: 2.2

CodePudding user response:

joinToString() lets you define a separator and modify each element of an Iterable to create a single string. The separator is a comma and space by default, so in this case you don't need to specify that. You can call it on the entries of a Map.

m.entries.joinToString { "${it.key}: ${it.value}" }
    .run(::println)

CodePudding user response:

How about this?

val m = mapOf("Juice" to 4.5, "Wine" to 8.0, "Soda" to 2.2)
println(m.map { "${it.key}: ${it.value}" }.joinToString(", "))

This prints:

Juice: 4.5, Wine: 8.0, Soda: 2.2
  • Related