Associating by a Key
Part of the Logic & Flow section of Coddy's Kotlin journey. Lesson 39 of 63.
associateBy creates a map from a computed key to an original element. If keys repeat, the last element for that key wins. Use groupBy when every matching element must survive; use associateBy when one latest element per key is intended.
Inside main:
val latest = listOf("a", "to", "b").associateBy { it.length }
println(latest[1])Both a and b have key one, so b replaces a for that key.
associateBy keeps the last element when computed keys collide.
Challenge
MediumComplete lastOfLength with parameters words: List<String>, length: Int. Use associateBy with word length as the key. Return the last input word of the requested length, or missing if none exists.
Unless stricter bounds are stated above, collections contain at most 100 elements at each level, and integer arguments and integer collection values are between -1000 and 1000. Text supplied for parsing can include invalid or out-of-range representations as described.
Return a value of type String. Keep the supplied input/output code. It reads scalar arguments one per line; a list starts with its count followed by its elements, and a map starts with its entry count followed by each key and value. Nested lists repeat the count-and-elements format for each row. The supplied main prints the return value followed by one newline. Lists use Kotlin's standard bracketed format; print no additional labels.
Try it yourself
fun lastOfLength(words: List<String>, length: Int): String {
// Write your solution here.
return ""
}
fun main() {
val wordsCount = readln().toInt()
val words = mutableListOf<String>()
for (i0 in 0 until wordsCount) {
val wordsItem = readLine().orEmpty()
words.add(wordsItem)
}
val length = readln().toInt()
println(lastOfLength(words, length))
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
4Nested Collections
Lists of ListsTraversing RowsRow SummariesFlattening Nested ListsRecap - Seating Rows7Collection Pipelines
Transforming with MapFiltering ValuesTesting Collection RulesAccumulating with FoldRecap - Approved Totals5Project - Contact Book
Save ContactsFind Contacts8Sorting and Grouping
Sorting by a KeyCombining ComparisonsGrouping ValuesAssociating by a KeyRecap - Length LeaderboardPractice on your own: Kotlin playground