Kotlin Set toMap()
Syntax & Examples
Set.toMap() extension function
The toMap() extension function in Kotlin returns a new map containing all key-value pairs from the given collection of pairs. It can also populate and return the destination mutable map with key-value pairs from the given collection of pairs.
Syntax of Set.toMap()
There are 2 variations for the syntax of Set.toMap() extension function. They are:
fun <K, V> Iterable<Pair<K, V>>.toMap(): Map<K, V>
This extension function returns a new map containing all key-value pairs from the given collection of pairs.
Returns value of type Map<K, V>
.
fun <K, V, M : MutableMap<in K, in V>> Iterable<Pair<K, V>>.toMap(destination: M): M
This extension function populates and returns the destination mutable map with key-value pairs from the given collection of pairs.
Returns value of type M
.
✐ Examples
1 Converting a set of pairs to a map
Using toMap() to convert a set of pairs to a map.
For example,
- Create a set of pairs.
- Use toMap() to convert the set to a map.
- Print the resulting map.
Kotlin Program
fun main() {
val pairs = setOf(Pair("one", 1), Pair("two", 2), Pair("three", 3))
val map = pairs.toMap()
println(map)
}
Output
{one=1, two=2, three=3}
2 Populating a mutable map with key-value pairs from a set of pairs
Using toMap() to populate a mutable map with key-value pairs from a set of pairs.
For example,
- Create a set of pairs.
- Create a mutable map.
- Use toMap() to populate the mutable map with key-value pairs from the set of pairs.
- Print the resulting map.
Kotlin Program
fun main() {
val pairs = setOf(Pair("one", 1), Pair("two", 2), Pair("three", 3))
val destination = mutableMapOf<String, Int>()
pairs.toMap(destination)
println(destination)
}
Output
{one=1, two=2, three=3}
3 Converting a set of pairs with custom objects to a map
Using toMap() to convert a set of pairs with custom objects to a map.
For example,
- Create a data class.
- Create a set of pairs with custom objects.
- Use toMap() to convert the set to a map.
- Print the resulting map.
Kotlin Program
data class Person(val name: String, val age: Int)
fun main() {
val pairs = setOf(Pair(Person("Alice", 30), 1), Pair(Person("Bob", 25), 2), Pair(Person("Charlie", 35), 3))
val map = pairs.toMap()
println(map)
}
Output
{Person(name=Alice, age=30)=1, Person(name=Bob, age=25)=2, Person(name=Charlie, age=35)=3}
Summary
In this Kotlin tutorial, we learned about toMap() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.