Challenge - 5 Problems
Associate Map Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this Kotlin code using associate?
Consider the following Kotlin code snippet that creates a map from a list of strings using
associate. What will be printed?Kotlin
val fruits = listOf("apple", "banana", "cherry") val map = fruits.associate { it to it.length } println(map)
Attempts:
2 left
💡 Hint
Remember that
associate creates a map where each key-value pair is defined by the lambda.✗ Incorrect
The associate function creates a map where each string is the key and its length is the value. The lengths are correct as apple=5, banana=6, cherry=6.
❓ Predict Output
intermediate2:00remaining
What does this Kotlin code print when using associateBy?
Look at this Kotlin code that uses
associateBy. What is the output?Kotlin
data class Person(val name: String, val age: Int) val people = listOf(Person("Alice", 30), Person("Bob", 25), Person("Charlie", 30)) val map = people.associateBy { it.age } println(map)
Attempts:
2 left
💡 Hint
When keys are duplicated, the last element wins in
associateBy.✗ Incorrect
associateBy creates a map where the key is the age. Since two people have age 30, the last one (Charlie) overwrites Alice.
🔧 Debug
advanced2:00remaining
Why does this Kotlin code cause a compilation error?
Examine this Kotlin code snippet. It tries to create a map using
associate but fails to compile. What is the cause?Kotlin
val numbers = listOf(1, 2, 3) val map = numbers.associate { it * 2 } println(map)
Attempts:
2 left
💡 Hint
Check what the lambda inside
associate should return.✗ Incorrect
The associate function expects the lambda to return a Pair<K, V> for each element. Returning just an Int causes a compilation error.
❓ Predict Output
advanced2:00remaining
What is the output of this Kotlin code using associateWith?
Given this Kotlin code using
associateWith, what will be printed?Kotlin
val words = listOf("one", "two", "three") val map = words.associateWith { it.length } println(map)
Attempts:
2 left
💡 Hint
associateWith creates a map where each element is the key and the lambda result is the value.✗ Incorrect
The map keys are the words themselves, and the values are their lengths: one=3, two=3, three=5.
🧠 Conceptual
expert2:00remaining
How many entries are in the map created by this Kotlin code?
Consider this Kotlin code that creates a map from a list of pairs using
associate. How many entries will the resulting map have?Kotlin
val pairs = listOf("a" to 1, "b" to 2, "a" to 3, "c" to 4) val map = pairs.associate { it } println(map.size)
Attempts:
2 left
💡 Hint
When keys repeat, the last value overwrites previous ones in a map.
✗ Incorrect
The key "a" appears twice. The last value (3) overwrites the first (1). So keys are "a", "b", "c" → 3 entries.