Create map where each key has more that one value

I want to kown that is some way to create a map where each key has more that one value in the idiomatic way
Someone knows how create a map, where each key has more that one value?
for simplify the process of do this:

val map = mapOf( 1 to "one",  1 to "1" )

I am undertand that each key need have one value, in this way I am only change the value of key 1

Sounds like you need a MultiMap, which can be emulated with a Map<Int, Set<String>>


Really depends on what syntax you want, I suppose. You could simply create a function that accepts a key and vararg values, and use that, like so:

fun <K, V> entries(key: K, vararg values: V): Pair<K, List<V>> = key to values.toList()

    entries(1, "one", "1"),
    entries(2, "two", "2")

I don’t think there’s a way to do it without calling an extra function… since to is an infix function and as far as I understand, infix functions only ever take one argument on the right hand side. Otherwise you could do something like:

infix fun <K, V> values: V): Pair<K, List<V>> = this to values.toList()

Pretty sure Kotlin wouldn’t accept that, though. :slight_smile:

1 Like

I prefer kyay10’s idea, but with List instead of String. Here is an example.

val multimap: Map<Int, List<String>> =
    mapOf(1 to listOf("1", "one"),
         (2 to listOf("2", "two")))
println(multimap)   // output: {1=[1, one], 2=[2, two]}
1 Like