Kotlin Map keys
Syntax & Examples
Syntax of Map.keys
The syntax of Map.keys property is:
abstract val keys: Set<K>
This keys property of Map returns a read-only Set of all keys in this map.
✐ Examples
1 Get keys from map of numbers and characters
In this example,
- We create a map named
map
containing pairs of numbers and characters. - We then access the keys using the
keys
property. - The keys are printed to standard output.
Kotlin Program
fun main(args: Array<String>) {
val map = mapOf(1 to 'a', 2 to 'b', 3 to 'c')
val keys = map.keys
println(keys)
}
Output
[1, 2, 3]
2 Get keys from map of characters and numbers
In this example,
- We create a map named
map
containing pairs of characters and numbers. - We then access the keys using the
keys
property. - The keys are printed to standard output.
Kotlin Program
fun main(args: Array<String>) {
val map = mapOf('a' to 1, 'b' to 2, 'c' to 3)
val keys = map.keys
println(keys)
}
Output
[a, b, c]
3 Get keys from map of strings and numbers
In this example,
- We create a map named
map
containing pairs of strings and numbers. - We then access the keys using the
keys
property. - The keys are printed to standard output.
Kotlin Program
fun main(args: Array<String>) {
val map = mapOf("apple" to 1, "banana" to 2, "cherry" to 3)
val keys = map.keys
println(keys)
}
Output
[apple, banana, cherry]
Summary
In this Kotlin tutorial, we learned about keys property of Map: the syntax and few working examples with output and detailed explanation for each example.