Reputation: 1676
I want to create a mutable map whose keys fall in a continuous range, and values initially set to the same value 9 in a single line using Kotlin. How to do that?
Upvotes: 1
Views: 2456
Reputation: 147911
One more option not mentioned in the other answers is to use the associate*
function that takes the argument collection that it will put the pairs to:
val result = (1..9).associateWithTo(mutableMapOf()) { 9 }
Unlike .associateWith { ... }.toMutableMap()
, this doesn't copy the collection.
If you need to use a different implementation (e.g. a HashMap()
), you can pass it to this function, like .associateWithTo(HashMap()) { ... }
.
Many collection processing functions in the Kotlin standard library follow this pattern and have a counterpart with an additional parameter accepting the collection where the results will be put. For example: map
and mapTo
, filter
and filterTo
, associate
and associateTo
.
Upvotes: 2
Reputation: 7163
I would use associateWith:
val map = (1..9).associateWith { 9 }.toMutableMap()
println(map) // {1=9, 2=9, 3=9, 4=9, 5=9, 6=9, 7=9, 8=9, 9=9}
It also works with other types as key, like Char:
val map = ('a'..'z').associateWith { 9 }.toMutableMap()
println(map) // {a=9, b=9, c=9, d=9, e=9, f=9, g=9, h=9, i=9}
Upvotes: 1
Reputation: 12953
You can try the following:
val map = object : HashMap<Int, Int>() {
init {
(1..10).forEach {
put(it, 9)
}
}
}
println(map)
Upvotes: 1
Reputation: 4204
If you mean values, you can use the withDefault
function on any Map / MutableMap:
fun main() {
val map = mutableMapOf<String, Int>().withDefault { 9 }
map["hello"] = 5
println(map.getValue("hello"))
println(map.getValue("test"))
}
Upvotes: 1
Reputation: 1676
You can use the following way:
import java.util.*
fun main(args: Array<String>) {
val a :Int = 0
val b :Int = 7
val myMap = mutableMapOf<IntRange, Int>()
myMap[a..b] = 9
myMap.toMap()
println(myMap) //Output: {0..7=9}
}
Upvotes: -1