filterKeys

Common
JVM
JS
Native
1.0
inline fun <K, V> Map<out K, V>.filterKeys(
    predicate: (K) -> Boolean
): Map<K, V>

(source)

Returns a map containing all key-value pairs with keys matching the given predicate.

The returned map preserves the entry iteration order of the original map.

import kotlin.test.*
import java.util.*

fun main(args: Array<String>) {
//sampleStart
val originalMap = mapOf("key1" to 1, "key2" to 2, "something_else" to 3)

val filteredMap = originalMap.filterKeys { it.contains("key") }
println(filteredMap) // {key1=1, key2=2}
// original map has not changed
println(originalMap) // {key1=1, key2=2, something_else=3}

val nonMatchingPredicate: (String) -> Boolean = { it == "key3" }
val emptyMap = originalMap.filterKeys(nonMatchingPredicate)
println(emptyMap) // {}
//sampleEnd
}