Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Kotlin
Stage 5: Specialization

Part 06 / Topic 5 of 7

Common operations across List, Set and Map

A handful of operations work the same way regardless of which of the three you're holding — learn them once here instead of re-learning them per type.

val list = mutableListOf("Rice", "Dal", "Atta")
val set = mutableSetOf("Rice", "Dal", "Atta")
val map = mutableMapOf("Rice" to 68.0, "Dal" to 145.0)

println("list.size: ${list.size}, set.size: ${set.size}, map.size: ${map.size}")
println("list.isEmpty(): ${list.isEmpty()}, list.isNotEmpty(): ${list.isNotEmpty()}")
list.size: 3, set.size: 3, map.size: 2
list.isEmpty(): false, list.isNotEmpty(): true

contains/in works the same way on all three; for a Map it checks keys, same as containsKey:

println("\"Dal\" in list: ${"Dal" in list}")
println("\"Dal\" in set: ${"Dal" in set}")
println("\"Dal\" in map: ${"Dal" in map}")          // checks keys
println("map.containsValue(68.0): ${map.containsValue(68.0)}")
"Dal" in list: true
"Dal" in set: true
"Dal" in map: true
map.containsValue(68.0): true

clear() empties any of the three in place, and a Map's keys, values and entries are each their own read-only view of it:

list.clear()
println("list after clear(): $list, isEmpty: ${list.isEmpty()}")
println("map.keys: ${map.keys}")
println("map.values: ${map.values}")
println("map.entries: ${map.entries}")
list after clear(): [], isEmpty: true
map.keys: [Rice, Dal]
map.values: [68.0, 145.0]
map.entries: [Rice=68.0, Dal=145.0]

🔍 Going deeper: Array<T> (arrayOf(...)) is a fourth option — fixed-size, closer to Java's T[], and mostly seen in this course where a JDK API itself demands one (fun main(args: Array<String>) is the one you've already met, in Part 1). listOf/mutableListOf is the everyday choice for your own code; reach for an array only when something outside your own code requires it.

val asArray = arrayOf("Rice", "Dal", "Atta")
println("arrayOf(...).toList(): ${asArray.toList()}")
arrayOf(...).toList(): [Rice, Dal, Atta]

Full program: examples/05_common_operations.kt.

Done here? The practice set for Part 6 — including the solutions — is on the part page.

Search the guide