Part 06 / Stage 1
Collections
Goal: Use
List,SetandMapas ready-made tools — build them withlistOf/mutableListOf/setOf/mutableSetOf/mapOf/mutableMapOf, tell the read-only interface apart from the mutable one, index and iterate them, and reach forcontains/add/remove/filter/map/sumOfwithout needing to know how a lambda works underneath yet. Time: ~5 hours · Level: comfortable with functions (Part 5) and everything before it
What you will learn
List/MutableList: building withlistOf/mutableListOf, indexing, iterating,withIndex()- Why
Listis a read-only view, not a separate immutable type — and what that means in practice Set/MutableSet: uniqueness as the whole point,contains/in,toSet()to de-duplicate a listMap/MutableMap: key-value pairs built withto, lookup by key, destructuring a map in aforloop, and whymapOf/mutableMapOfalready keep insertion order on the JVM- The same handful of operations —
contains,add,remove,size,isEmpty,clear— working the same way across all three collection types filter,mapandsumOfused as ready-made tools, the way you'd use a calculator without caring how it's built — Stage 2 Part 10 (Functional Kotlin) is where lambdas themselves get a proper treatment- Building a shopping cart: a read-only catalog and a mutable cart, driven by a menu
Topics in this part
Practice
Try each one yourself first. Then check the solution.
Every exercise is one file with a top-level fun main(), using only what Parts 1–6 have covered so
far: val/var, basic types, null safety, control flow, functions, and this part's List/Set/Map.
No classes of your own yet — those start in Part 7.
Exercise 1: Kirana shelf
Scenario: a Pune kirana store owner keeps today's staple items listed in shelf order.
What to do: write val shelfItems = listOf("Rice", "Dal", "Atta", "Sugar", "Tea"), then print the
first item, the item at position 3 (1-based, so index 2), and the total number of items on the shelf.
Sample output:
First item: Rice
Item at position 3: Atta
Total items on shelf: 5
💡 Hint: shelfItems[0] is the first item; .size is the count. No loop needed for this one.
Exercise 2: Grocery list edits
Scenario: before heading to the kirana store, Priya edits her grocery list twice: she adds one item
at the end, inserts another at a specific position, and removes something she already has at home.
What to do: write val list = mutableListOf("Milk", "Bread"), add "Eggs" at the end, insert
"Butter" at position 1 (shifting "Bread" along), remove "Bread", then print the final list.
Sample output:
[Milk, Butter, Eggs]
💡 Hint: list.add(1, "Butter") inserts at a position; plain list.add("Eggs") appends.
Exercise 3: Unique pincodes served
Scenario: a Bengaluru courier company logs the delivery pincode for every scooter trip in a day;
the same area gets several deliveries, so the log has plenty of repeats.
What to do: write
val deliveries = listOf("560001", "560034", "560001", "560066", "560034", "560001"), convert it to a
Set with .toSet(), then print the unique pincodes, how many there are, and whether "560100" was
among them.
Sample output:
Unique pincodes served: [560001, 560034, 560066]
Count: 3
Served 560100: false
💡 Hint: deliveries.toSet() drops the repeats for you; in checks membership on the result.
Exercise 4: Vegetable price board
Scenario: a vegetable vendor keeps today's per-kilo prices on a small board.
What to do: write val prices = mapOf("Tomato" to 40, "Onion" to 35, "Potato" to 28). Print the
price of "Onion", then the price of "Brinjal" (not on the board) using ?: 0 so a missing item
doesn't print null. Finally, loop over the whole board and print one line per item.
Sample output:
Price of Onion: ₹35/kg
Price of Brinjal: ₹0/kg
Tomato costs ₹40/kg
Onion costs ₹35/kg
Potato costs ₹28/kg
💡 Hint: for ((item, price) in prices) destructures each entry directly into two names.
Exercise 5: Prove the view, not the copy
Scenario: section 2's README showed a List being a read-only view over a MutableList, not an
independent copy. Reproduce that yourself, with a wishlist instead of a shopping cart.
What to do: write val realWishlist = mutableListOf("Kurta", "Saree"), store it in
val readOnlyWishlist: List<String> = realWishlist, print it, then realWishlist.add("Shawl") and
print readOnlyWishlist again to show it changed too. Finally, cast readOnlyWishlist back to
MutableList<String> and add "Jutti" through that cast, then print both names once more.
Sample output:
Before: readOnlyWishlist = [Kurta, Saree]
After realWishlist.add: readOnlyWishlist = [Kurta, Saree, Shawl]
After cast-and-add: readOnlyWishlist = [Kurta, Saree, Shawl, Jutti], realWishlist = [Kurta, Saree, Shawl, Jutti]
💡 Hint: @Suppress("UNCHECKED_CAST") above the cast line keeps the compiler quiet about the
generic cast; the point of the exercise is to see what happens at runtime, not to avoid the cast.
Exercise 6: Diwali shopping budget
Scenario: a Diwali shopping list has a mix of cheap and expensive items, and the budget question is specifically about the pricier ones. What to do: write
val prices = mapOf(
"Diya set" to 150,
"Rangoli colours" to 80,
"Sweets box" to 450,
"LED lights" to 299,
"Greeting card" to 40
)
Use .filter { ... } to keep only the items priced above ₹100, print that map, then use .sumOf { ... }
on its values to print the total spend on just those items. Finally, use .map { ... } to print a list
of "item: ₹price" strings for every item on the original list.
Sample output:
Items above ₹100: {Diya set=150, Sweets box=450, LED lights=299}
Total spend on items above ₹100: ₹899
[Diya set: ₹150, Rangoli colours: ₹80, Sweets box: ₹450, LED lights: ₹299, Greeting card: ₹40]
💡 Hint: prices.filter { (_, price) -> price > 100 } destructures each entry right in the lambda
parameter; itemsAbove100.values.sumOf { it } adds up what's left after filtering.
Exercise 7: Kirana bestsellers
Scenario: a kirana store's point-of-sale system logs every single sale as an (item, quantity)
pair, in no particular grouping — the same item appears several times across the day.
What to do: given
val prices = mapOf("Rice (kg)" to 68, "Dal (kg)" to 145, "Atta (kg)" to 52, "Sugar (kg)" to 45)
val sales = listOf(
"Rice (kg)" to 2, "Dal (kg)" to 1, "Rice (kg)" to 3,
"Sugar (kg)" to 6, "Atta (kg)" to 4, "Dal (kg)" to 2, "Sugar (kg)" to 1
)
build a mutableMapOf<String, Int>() of total quantity sold per item (looping over sales and adding
to whatever's already there), print it; print the distinct items sold as a Set (.map { ... }.toSet()
over sales); then .filter { ... } the totals map down to items that sold 5 or more units, print that,
and use .sumOf { ... } over its entries (multiplying quantity by price from prices) to print the
revenue from just the bestsellers.
Sample output:
Total quantity sold per item: {Rice (kg)=5, Dal (kg)=3, Sugar (kg)=7, Atta (kg)=4}
Distinct items sold: [Rice (kg), Dal (kg), Sugar (kg), Atta (kg)]
Bestsellers (5+ units): {Rice (kg)=5, Sugar (kg)=7}
Revenue from bestsellers: ₹655
💡 Hint: totalsByItem[item] = (totalsByItem[item] ?: 0) + qty is the same "update or insert"
pattern as the shopping cart's cart[item] = (cart[item] ?: 0) + qty; 655 is 5 x 68 + 7 x 45.
Show the solutions for Part 6 (7 files)
solutions/ex01.kt
fun main() {
val shelfItems = listOf("Rice", "Dal", "Atta", "Sugar", "Tea")
println("First item: ${shelfItems[0]}")
println("Item at position 3: ${shelfItems[2]}")
println("Total items on shelf: ${shelfItems.size}")
}
solutions/ex02.kt
fun main() {
val list = mutableListOf("Milk", "Bread")
list.add("Eggs")
list.add(1, "Butter")
list.remove("Bread")
println(list)
}
solutions/ex03.kt
fun main() {
val deliveries = listOf("560001", "560034", "560001", "560066", "560034", "560001")
val uniquePincodes = deliveries.toSet()
println("Unique pincodes served: $uniquePincodes")
println("Count: ${uniquePincodes.size}")
println("Served 560100: ${"560100" in uniquePincodes}")
}
solutions/ex04.kt
fun main() {
val prices = mapOf("Tomato" to 40, "Onion" to 35, "Potato" to 28)
println("Price of Onion: ₹${prices["Onion"]}/kg")
println("Price of Brinjal: ₹${prices["Brinjal"] ?: 0}/kg")
for ((item, price) in prices) {
println("$item costs ₹$price/kg")
}
}
solutions/ex05.kt
fun main() {
val realWishlist = mutableListOf("Kurta", "Saree")
val readOnlyWishlist: List<String> = realWishlist
println("Before: readOnlyWishlist = $readOnlyWishlist")
realWishlist.add("Shawl")
println("After realWishlist.add: readOnlyWishlist = $readOnlyWishlist")
@Suppress("UNCHECKED_CAST")
(readOnlyWishlist as MutableList<String>).add("Jutti")
println("After cast-and-add: readOnlyWishlist = $readOnlyWishlist, realWishlist = $realWishlist")
}
solutions/ex06.kt
fun main() {
val prices = mapOf(
"Diya set" to 150,
"Rangoli colours" to 80,
"Sweets box" to 450,
"LED lights" to 299,
"Greeting card" to 40
)
val itemsAbove100 = prices.filter { (_, price) -> price > 100 }
println("Items above ₹100: $itemsAbove100")
val totalAbove100 = itemsAbove100.values.sumOf { it }
println("Total spend on items above ₹100: ₹$totalAbove100")
val labelled = prices.map { (item, price) -> "$item: ₹$price" }
println(labelled)
}
solutions/ex07.kt
fun main() {
val prices = mapOf("Rice (kg)" to 68, "Dal (kg)" to 145, "Atta (kg)" to 52, "Sugar (kg)" to 45)
val sales = listOf(
"Rice (kg)" to 2, "Dal (kg)" to 1, "Rice (kg)" to 3,
"Sugar (kg)" to 6, "Atta (kg)" to 4, "Dal (kg)" to 2, "Sugar (kg)" to 1
)
val totalsByItem = mutableMapOf<String, Int>()
for ((item, qty) in sales) {
totalsByItem[item] = (totalsByItem[item] ?: 0) + qty
}
println("Total quantity sold per item: $totalsByItem")
val distinctItemsSold = sales.map { (item, _) -> item }.toSet()
println("Distinct items sold: $distinctItemsSold")
val bestsellers = totalsByItem.filter { (_, qty) -> qty >= 5 }
println("Bestsellers (5+ units): $bestsellers")
val bestsellerRevenue = bestsellers.entries.sumOf { (item, qty) -> (prices[item] ?: 0) * qty }
println("Revenue from bestsellers: ₹$bestsellerRevenue")
}
Common mistakes
| Mistake | Why it is wrong | Fix |
|---|---|---|
Calling .add()/.remove() on a value typed List/Set/Map |
Those interfaces simply don't declare those methods — it's a compile error, not a runtime check | Use mutableListOf/mutableSetOf/mutableMapOf (or a type declared as MutableList/etc.) when you need to change it |
Assuming a List-typed val is a safe, independent snapshot |
It may be a read-only view of a MutableList someone else still holds and can change |
Call .toList() (or .toSet()/.toMap()) to make a genuinely independent copy when that's what you need |
Reading map["missing key"] and using the result directly |
[] on a Map returns String?/T? — a missing key is null, not an exception |
Handle it with ?: or getOrDefault, same habit as Part 3's null safety |
Expecting setOf(...)/mutableSetOf(...) iteration order to be random, "HashSet-style" |
Kotlin's default builders use LinkedHashSet/LinkedHashMap underneath, which keep insertion order |
Only hashSetOf/hashMapOf opt into the genuinely unordered JDK types — avoid them unless you specifically want that |
Writing cart[item] = qty to "add more" of an existing item |
This replaces the quantity, it doesn't add to it | cart[item] = (cart[item] ?: 0) + qty reads the current value first |
Treating filter/map as changing the original list in place |
Both return a new collection; the original is untouched | Assign the result to a new val, same as any other expression |
Reaching for arrayOf(...) out of habit from another language |
Array<T> is fixed-size and closer to Java's T[]; it's rarely what you want for your own code |
Use listOf/mutableListOf unless a JDK/Java API specifically asks for an array |
Quick recap
List/Set/Mapeach have a read-only interface and aMutable...one;listOf/setOf/mapOfbuild the read-only kind,mutableListOf/mutableSetOf/mutableMapOfbuild the mutable kind.- A read-only
List/Set/Mapcan still be a view over a mutable collection someone else holds — read-only is a type-level promise, not a guarantee the data can never change underneath you. Setguarantees no duplicates;Mapstores key-value pairs built withtoand looked up with[], which returnsnullfor a missing key.mapOf/mutableMapOf/setOf/mutableSetOfall keep insertion order on the JVM by default — checked by inspecting the runtime class, not assumed.contains/in,add,remove,size,isEmpty,clearwork the same way across all three types.filter,mapandsumOfare ready-made tools for now; Stage 2 Part 10 explains lambdas properly.
Checklist
- I built a
ListwithlistOf, indexed into it, and iterated it with both a plainforandwithIndex(). - I proved for myself that a read-only
Listcan be a view over aMutableList, not a copy. - I built a
Setand used it to de-duplicate a list withtoSet(). - I built a
MapwithmapOf, looked up a missing key safely, and destructured entries in aforloop. - I checked
mapOf's runtime class myself and confirmed it keeps insertion order. - I used
contains/add/remove/size/isEmpty/clearacross aList, aSetand aMap. - I used
filter,mapandsumOfon both a list and a map's entries. - I built and ran the shopping cart myself, including a checkout and an invalid-item attempt.