Kotlin Set associateWith()
Syntax & Examples
Set.associateWith() extension function
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.
Syntax of Set.associateWith()
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.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
valueSelector | required | A function that takes an element of the set and returns a value for the resulting map. |
Return Type
Set.associateWith() returns value of type Map
.
✐ Examples
1 Using associateWith() to create a map from a set of strings
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,
- Create a set of strings.
- Use the
associateWith()
function with a valueSelector function that returns the length of the string. - Print the resulting map to the console using the
println
function.
Kotlin Program
fun main(args: Array<String>) {
val fruits = setOf("apple", "banana", "cherry")
val fruitLengths = fruits.associateWith { it.length }
println("Fruit lengths: $fruitLengths")
}
Output
Fruit lengths: {apple=5, banana=6, cherry=6}
2 Using associateWith() to create a map from a set of integers
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,
- Create a set of integers.
- Use the
associateWith()
function with a valueSelector function that returns the square of the integer. - Print the resulting map to the console using the
println
function.
Kotlin Program
fun main(args: Array<String>) {
val numbers = setOf(1, 2, 3, 4, 5)
val squares = numbers.associateWith { it * it }
println("Number squares: $squares")
}
Output
Number squares: {1=1, 2=4, 3=9, 4=16, 5=25}
3 Using associateWith() with an empty set
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,
- Create an empty set of integers.
- Use the
associateWith()
function with a valueSelector function that returns the square of the integer. - Print the resulting map to the console using the
println
function.
Kotlin Program
fun main(args: Array<String>) {
val emptySet = emptySet<Int>()
val squares = emptySet.associateWith { it * it }
println("Number squares in empty set: $squares")
}
Output
Number squares in empty set: {}
Summary
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.