Is there Multimap in Kotlin?

You could also use: val myMap = LinkedMultiValueMap<String, String>().apply {add("Hello", "World")}


No, there currently isn't. And there probably won't be one in the future.

Reference: https://discuss.kotlinlang.org/t/the-standard-library-and-a-kotlin-manifesto/1303/6

Alternative:

org.springframework.util.MultiValueMap
org.apache.commons.collections4.MultiMap
com.google.common.collect.Multimap

To play with the Set in your example, you can:

map["key"].forEach(::println)

Or something else.


If you use Kotlin on the JVM and Spring: you can use the collectionUtils for MultivalueMap: and you can also get an unmodifiable type: which in reality just throws UnsupportedOperationException on the modifications.

val myMap = mapOf("1" to listOf(1,2,3))
CollectionUtils.unmodifiableMultiValueMap(CollectionUtils.toMultiValueMap(myMap))

But it is hard to interact with Set inside the map.

It's not that hard, e.g.:

val map = HashMap<String, MutableSet<String>>()
map.getOrPut("howdy") { mutableSetOf() }.add("world")

Tags:

Kotlin