Kotlin Map values
Syntax & Examples
Syntax of Map.values
The syntax of Map.values property is:
abstract val values: Collection<V>
This values property of Map returns a read-only Collection of all values in this map. Note that this collection may contain duplicate values.
✐ Examples
1 Get values 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
values
property of the map to get a read-only Collection of values. - We then print the values to standard output.
Kotlin Program
fun main(args: Array<String>) {
val map = mapOf(1 to 'a', 2 to 'b', 3 to 'c')
val values = map.values
println(values)
}
Output
[a, b, c]
2 Get values 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
values
property of the map to get a read-only Collection of values. - We then print the values to standard output.
Kotlin Program
fun main(args: Array<String>) {
val map = mapOf("apple" to 1, "banana" to 2, "cherry" to 3)
val values = map.values
println(values)
}
Output
[1, 2, 3]
3 Print values of a map using a loop
In this example,
- We create a map named
map
with integer keys and character values. - We use a
for
loop to iterate over each value inmap.values
. - We print each value to standard output.
Kotlin Program
fun main(args: Array<String>) {
val map = mapOf(1 to 'a', 2 to 'b', 3 to 'c')
for (value in map.values) {
println(value)
}
}
Output
a b c
Summary
In this Kotlin tutorial, we learned about values property of Map: the syntax and few working examples with output and detailed explanation for each example.