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?
- 
                    Can you add an example map? If it's keys, there can only be one unique key. – LeoDog896 Jun 01 '22 at 00:05
5 Answers
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.
 
    
    - 140,743
- 39
- 371
- 326
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"))
}
 
    
    - 3,472
- 1
- 15
- 40
You can try the following:
val map = object : HashMap<Int, Int>() {
    init {
        (1..10).forEach {
            put(it, 9)
        }
    }
}
println(map)
 
    
    - 12,667
- 7
- 37
- 64
- 
                    Note that this solution might have unexpected side effects: it creates a new class extending `HashMap`, which might not be desirable. See https://stackoverflow.com/a/6802502/2196460 and https://wiki.c2.com/?DoubleBraceInitialization – hotkey Jun 01 '22 at 09:34
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}
 
    
    - 6,453
- 2
- 5
- 24
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}
}
 
    
    - 1,478
- 9
- 25
- 
                    val params: MutableMap= HashMap – Ashwin H Jul 26 '22 at 10:10() params.put("1", "A") params.put("2", "B")