The syntax of Map.toList() extension function is:
fun <K, V> Map<out K, V>.toList(): List<Pair<K, V>>
This toList() extension function of Map returns a List containing all key-value pairs.
In this example,
map1
containing key-value pairs 1 to 'a'
, 2 to 'b'
, and 3 to 'c'
.toList()
function on map1
to convert the map entries into a list of pairs.fun main(args: Array<String>) {
val map1 = mapOf(1 to 'a', 2 to 'b', 3 to 'c');
val result = map1.toList()
print(result);
}
[(1, a), (2, b), (3, c)]
In this example,
map2
containing key-value pairs 'a' to 1
, 'b' to 2
, and 'c' to 3
.toList()
function on map2
to convert the map entries into a list of pairs.fun main(args: Array<String>) {
val map2 = mapOf('a' to 1, 'b' to 2, 'c' to 3);
val result = map2.toList()
print(result);
}
[(a, 1), (b, 2), (c, 3)]
In this example,
map3
containing key-value pairs 1 to "apple"
, 2 to "banana"
, and 3 to "cherry"
.toList()
function on map3
to convert the map entries into a list of pairs.fun main(args: Array<String>) {
val map3 = mapOf(1 to "apple", 2 to "banana", 3 to "cherry");
val result = map3.toList()
print(result);
}
[(1, apple), (2, banana), (3, cherry)]
In this Kotlin tutorial, we learned about toList() extension function of Map: the syntax and few working examples with output and detailed explanation for each example.