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