W3cubDocs

/Kotlin

filterKeys

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

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
}

© 2010–2020 JetBrains s.r.o. and Kotlin Programming Language contributors
Licensed under the Apache License, Version 2.0.
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/filter-keys.html