Ansh Tyagi
11/17/2021, 9:24 PMMultiMap
in Kotlin? I wanted to reproduce the following guava data structure into native data structure
MultimapBuilder.treeKeys().arrayListValues().build<Int, Move>()
Joffrey
11/17/2021, 10:10 PMMap<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 withPaul Griffith
11/17/2021, 10:14 PMwithDefault
that make things a bit nicer to use:
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>Joffrey
11/17/2021, 10:16 PMwithDefault
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)mcpiroman
11/18/2021, 10:39 AMfun <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
}
}