The associate() extension function for sets in Kotlin returns a Map containing key-value pairs provided by a transform function applied to the elements of the set.
The syntax of Set.associate() extension function is:
fun <T, K, V> Set<T>.associate(transform: (T) -> Pair<K, V>): Map<K, V>
This associate() extension function of Set returns a Map containing key-value pairs provided by the transform function applied to elements of the given set.
Parameter | Optional/Required | Description |
---|---|---|
transform | required | A function that takes an element of the set and returns a Pair of key and value to be included in the resulting Map. |
Set.associate() returns value of type Map
.
In Kotlin, we can use the associate()
function to create a map from a set of strings, where the keys are the strings and the values are their lengths.
For example,
associate()
function with a transform function that returns a pair of the string and its length.println
function.fun main(args: Array<String>) {
val fruits = setOf("apple", "banana", "cherry")
val fruitLengths = fruits.associate { it to it.length }
println("Fruit lengths: $fruitLengths")
}
Fruit lengths: {apple=5, banana=6, cherry=6}
In Kotlin, we can use the associate()
function to create a map from a set of integers, where the keys are the integers and the values are their squares.
For example,
associate()
function with a transform function that returns a pair of the integer and its square.println
function.fun main(args: Array<String>) {
val numbers = setOf(1, 2, 3, 4, 5)
val squares = numbers.associate { it to it * it }
println("Number squares: $squares")
}
Number squares: {1=1, 2=4, 3=9, 4=16, 5=25}
In Kotlin, we can use the associate()
function to create a map from an empty set, which will result in an empty map.
For example,
associate()
function with a transform function that returns a pair of the integer and its square.println
function.fun main(args: Array<String>) {
val emptySet = emptySet<Int>()
val squares = emptySet.associate { it to it * it }
println("Number squares in empty set: $squares")
}
Number squares in empty set: {}
In this Kotlin tutorial, we learned about associate() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.