Hey Everyone!, is there any `MultiMap` in Kotlin? ...
# stdlib
a
Hey Everyone!, is there any
MultiMap
in Kotlin? I wanted to reproduce the following guava data structure into native data structure
Copy code
MultimapBuilder.treeKeys().arrayListValues().build<Int, Move>()
j
I don't think there is such a thing in the Kotlin stdlib, but you can simply use
Map<Int, List<Move>>
or
MutableMap<Int, MutableList<Move>>
. The main benefit of actual
MultiMap
is probably the API for insertion, but I believe now there are sufficient utilities like
getOrPut
that make it easy enough to interact with
p
Yeah, depending on the API you need it's easy enough to just make one-offs. There's some helper functions, e.g.
withDefault
that make things a bit nicer to use:
Copy code
fun <K: Comparable<K>, V> simpleMultiMap(): MutableMap<K, List<V>> {
    return TreeMap<K, List<V>>().withDefault { mutableListOf() }
}
simpleMultiMap.getValue(key)
will always return a List<V>
j
I think
withDefault
on mutable maps won't help for inserting stuff though (the default mutable list will not be inserted into the map when you access a non-existing key)
1
m
FWIW I have created these helper functions that mimic the api of MultiMap:
Copy code
fun <K, V, C : MutableCollection<V>> MutableMap<K, C>.addAsMulti(key: K, value: V, createEmpty: () -> C) {
    computeIfAbsent(key) { createEmpty() }.add(value)
}

fun <K, V, C : MutableCollection<V>> MutableMap<K, C>.removeAsMulti(key: K, value: V) {
    computeIfPresent(key) { _, list ->
        list.remove(value)
        if (list.isEmpty()) null else list
    }
}
👍 1