Checking Keys
Part of the Logic & Flow section of Coddy's Kotlin journey. Lesson 4 of 63.
containsKey checks whether a key is present. containsValue searches values instead. Membership with key in map also checks keys. Keep these questions distinct when a key and a value have the same text.
Inside main:
val codes = mapOf("red" to "R")
println("R" in codes)R is a value, not a key. The only key is red.
Use containsKey or in for keys; use containsValue for values.
Challenge
MediumComplete keyExists with parameters stock: Map<String, Int>, key: String. Return whether key is present, including when its stored value is zero.
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 Boolean. 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 keyExists(stock: Map<String, Int>, key: String): Boolean {
// Write your solution here.
return false
}
fun main() {
val stockCount = readln().toInt()
val stock = mutableMapOf<String, Int>()
for (i0 in 0 until stockCount) {
val stockKey = readln()
val stockValue = readln().toInt()
stock[stockKey] = stockValue
}
val key = readLine().orEmpty()
println(keyExists(stock, key))
}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 ContactsPractice on your own: Kotlin playground