Kotlin Map toList()
Syntax & Examples
Syntax of Map.toList()
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.
✐ Examples
1 Convert map entries to list
In this example,
- We create a map named
map1containing key-value pairs1 to 'a',2 to 'b', and3 to 'c'. - We then apply the
toList()function onmap1to convert the map entries into a list of pairs. - The resulting list contains pairs representing the entries of the map.
- We print the result to standard output.
Kotlin Program
fun main(args: Array<String>) {
val map1 = mapOf(1 to 'a', 2 to 'b', 3 to 'c');
val result = map1.toList()
print(result);
}Output
[(1, a), (2, b), (3, c)]
2 Convert map entries to list
In this example,
- We create a map named
map2containing key-value pairs'a' to 1,'b' to 2, and'c' to 3. - We then apply the
toList()function onmap2to convert the map entries into a list of pairs. - The resulting list contains pairs representing the entries of the map.
- We print the result to standard output.
Kotlin Program
fun main(args: Array<String>) {
val map2 = mapOf('a' to 1, 'b' to 2, 'c' to 3);
val result = map2.toList()
print(result);
}Output
[(a, 1), (b, 2), (c, 3)]
3 Convert map entries to list
In this example,
- We create a map named
map3containing key-value pairs1 to "apple",2 to "banana", and3 to "cherry". - We then apply the
toList()function onmap3to convert the map entries into a list of pairs. - The resulting list contains pairs representing the entries of the map.
- We print the result to standard output.
Kotlin Program
fun main(args: Array<String>) {
val map3 = mapOf(1 to "apple", 2 to "banana", 3 to "cherry");
val result = map3.toList()
print(result);
}Output
[(1, apple), (2, banana), (3, cherry)]
Summary
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.