vagdevi k
vagdevi k

Reputation: 1676

How to create a MutableMap with all keys initially set to same value in Kotlin?

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

Answers (5)

hotkey
hotkey

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

lukas.j
lukas.j

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

Nongthonbam Tonthoi
Nongthonbam Tonthoi

Reputation: 12953

You can try the following:

val map = object : HashMap<Int, Int>() {
    init {
        (1..10).forEach {
            put(it, 9)
        }
    }
}
println(map)

Upvotes: 1

Tristan F.-R.
Tristan F.-R.

Reputation: 4204

If you mean values, you can use the withDefault function on any Map / MutableMap:

(Playground)

fun main() {
    val map = mutableMapOf<String, Int>().withDefault { 9 }
    
    map["hello"] = 5
    
    println(map.getValue("hello"))
    println(map.getValue("test"))
}

Upvotes: 1

vagdevi k
vagdevi k

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

Related Questions