Kotlin Map entries
Syntax & Examples
Syntax of Map.entries
The syntax of Map.entries property is:
abstract val entries: Set<Entry<K, V>>
This entries property of Map returns a read-only Set of all key/value pairs in this map.
✐ Examples
1 Get entries of a map with integer keys and character values
In this example,
- We create a map named
map
with integer keys and character values. - We access the
entries
property of the map to get a read-only Set of key/value pairs. - We then print the entries to standard output.
Kotlin Program
fun main(args: Array<String>) {
val map = mapOf(1 to 'a', 2 to 'b', 3 to 'c')
val entries = map.entries
println(entries)
}
Output
[1=a, 2=b, 3=c]
2 Get entries of a map with string keys and integer values
In this example,
- We create a map named
map
with string keys and integer values. - We access the
entries
property of the map to get a read-only Set of key/value pairs. - We then print the entries to standard output.
Kotlin Program
fun main(args: Array<String>) {
val map = mapOf("apple" to 1, "banana" to 2, "cherry" to 3)
val entries = map.entries
println(entries)
}
Output
[apple=1, banana=2, cherry=3]
3 Iterate over entries of a map and print key-value pairs
In this example,
- We create a map named
map
with integer keys and character values. - We use a
for
loop to iterate over each entry inmap.entries
. - For each entry, we extract the
key
andvalue
and print them to standard output.
Kotlin Program
fun main(args: Array<String>) {
val map = mapOf(1 to 'a', 2 to 'b', 3 to 'c')
for ((key, value) in map.entries) {
println("Key: $key, Value: $value")
}
}
Output
Key: 1, Value: a Key: 2, Value: b Key: 3, Value: c
Summary
In this Kotlin tutorial, we learned about entries property of Map: the syntax and few working examples with output and detailed explanation for each example.