Search code examples
dictionarykotlinslice

Slice a map given a list of keys in Kotlin


Given a map, and a list of keys

val abc = mapOf(1 to "a", 2 to "b", 3 to "c")
val keys = listOf(1, 2)

How do I a get a map containing only the key-value pairs specified by keys? Something like

val ab = abc.slice(keys)
// equivalent to mapOf(1 to "a", 2 to "b)

I'm looking for something a bit more elegant than

val ab = listOf(1, 2).map { it to abc[it] }.toMap()

For example, in Elixir:

abc = %{1 => "a", 2 => "b", 3 => "c"}
ab = Map.take(abc, [1, 2])
# equivalent to ab = %{1 => "a", 2 => "b"}

Solution

  • You can use filterKeys:

    val ab = abc.filterKeys { it in keys }
    

    And since it is Kotlin, you could even define your own extension function to achieve exactly what you imagined:

    fun <T> Map<T, *>.slice(keys: Iterable<T>) = filterKeys { it in keys }
    
    val ab = abc.slice(keys)