KOTLIN / CHAPTER 07

Maps, sets, and occurrence policies

Intermediate

Aggregate by keys without confusing missing data and zero totals.

By the end of this chapter

  • Use maps for accumulation
  • Use sets for membership
  • Preserve first-occurrence order deliberately

The idea

A map associates keys with values, while a set records membership without an additional value. For counting, read an existing total or zero, then store the updated total. A missing lookup and a stored zero can produce the same fallback result, so use containsKey when presence itself matters. Decide whether zero totals remain meaningful entries before removing anything from an aggregation.

A first-occurrence deduplicator combines a set of normalized keys with a result list. Add the original display value only when its key is seen for the first time. This preserves the input’s display order without relying on a particular map implementation’s traversal order. Normalization and deduplication are separate requirements: case-insensitive comparison should not automatically destroy the spelling that the interface intends to show.

Kotlin example
fun main(){ val counts=mutableMapOf<String,Int>(); for(word in listOf("red","blue","red")) counts[word]=(counts[word]?:0)+1; println(counts["red"]); println(counts.containsKey("green")) }
Result
2
false

Repeated red observations update one key, while a lookup policy does not insert unrelated absent keys.

Try it yourself

Keep the first spelling of each trimmed case-insensitive label using a key set and result list.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

What is printed?
val counts=mutableMapOf("a" to 0)
println(counts.containsKey("a"))
println(counts["b"] ?: 7)