Sobes.tech
Junior — Middle

How to extract the first element from a collection in Kotlin if its key matches a given value?

sobes.tech AI

Answer from AI

In Kotlin, if you have a collection of type Map and need to get the first element where the key matches a given value, you can use the filter or filterKeys function, and then take the first element with firstOrNull().

Example:

val map = mapOf("a" to 1, "b" to 2, "c" to 3)
val keyToFind = "b"

val firstEntry = map.entries.firstOrNull { it.key == keyToFind }
println(firstEntry) // Output: b=2

If the collection is not a Map, but a List or another collection, and the elements have a field or property that needs to be compared with the key, you can use firstOrNull with a condition:

data class Item(val key: String, val value: Int)

val list = listOf(Item("a", 1), Item("b", 2), Item("c", 3))
val keyToFind = "b"

val firstItem = list.firstOrNull { it.key == keyToFind }
println(firstItem) // Output: Item(key=b, value=2)

If the element is not found, firstOrNull will return null, which is convenient for safe handling.