A List is an ordered collection of elements that allows duplicates. Kotlin's List<T> interface represents read-only lists — you can read elements but cannot add or remove them.
Creating read-only listsfun main() {
val fruits = listOf("Apple", "Banana", "Cherry")
val numbers = listOf(10, 20, 30, 20)
println(fruits[0]) // Apple — index access
println(fruits.size) // 3
println(numbers.count()) // 4 — duplicates allowed
}
List creation functions
Function
Type
Description
listOf(...)
List (read-only)
Fixed elements, immutable view
emptyList()
List
Empty read-only list
List(n) { index -> ... }
List
Build list of size n
arrayListOf(...)
ArrayList (mutable)
Mutable array-backed list
Common list methodsfun main() {
val colors = listOf("Red", "Green", "Blue", "Green")
println(colors.first()) // Red
println(colors.last()) // Green
println(colors.indexOf("Green")) // 1
println(colors.contains("Blue")) // true
println(colors.distinct()) // [Red, Green, Blue]
}
Read-only vs immutable
List is read-only through the interface — the underlying list may still be mutable if created as mutableListOf and cast to List. Prefer listOf for truly fixed collections.
2Mutable Lists
A MutableList extends List with operations to add, remove, and update elements. Use mutableListOf() for the most common case.
RecyclerView / adapters: Mutable lists are commonly used to back adapter data — add/remove items then call notifyDataSetChanged() or DiffUtil in Android.
3Sets
A Set is an unordered collection of unique elements — no duplicates. Useful for membership checks, distinct values, and removing duplicates from lists.
Read-only and mutable setsfun main() {
val readOnly = setOf("Kotlin", "Java", "Kotlin") // duplicate ignored
println(readOnly) // [Kotlin, Java]
val mutable = mutableSetOf(1, 2, 3)
mutable.add(2) // duplicate — set unchanged
mutable.add(4)
println(mutable) // [1, 2, 3, 4]
}
Set types
Function
Implementation
Notes
setOf(...)
LinkedHashSet
Read-only, insertion order
mutableSetOf(...)
LinkedHashSet
Mutable, insertion order
hashSetOf(...)
HashSet
Mutable, no guaranteed order
sortedSetOf(...)
TreeSet
Mutable, sorted order
Set operationsfun main() {
val a = setOf(1, 2, 3)
val b = setOf(3, 4, 5)
println(a union b) // [1, 2, 3, 4, 5]
println(a intersect b) // [3]
println(a subtract b) // [1, 2]
println(2 in a) // true
}
Remove duplicates from list
list.distinct() returns a new list; list.toSet() converts to a set of unique elements.
4Maps
A Map stores key-value pairs. Each key maps to exactly one value. Keys must be unique; values can repeat.
Creating mapsfun main() {
val capitals = mapOf(
"India" to "New Delhi",
"USA" to "Washington D.C.",
"Japan" to "Tokyo"
)
println(capitals["India"]) // New Delhi
println(capitals.getOrDefault("UK", "Unknown")) // Unknown
println(capitals.keys) // [India, USA, Japan]
println(capitals.values) // [New Delhi, Washington D.C., Tokyo]
}
Mutable maps
mutableMapOffun main() {
val scores = mutableMapOf("Alice" to 95, "Bob" to 88)
scores["Charlie"] = 92 // add
scores["Bob"] = 90 // update
scores.remove("Alice")
for ((name, score) in scores) {
println("$name: $score")
}
}
Map creation and access
Function / syntax
Description
mapOf("a" to 1)
Read-only map
mutableMapOf()
Empty mutable map
map[key]
Returns value or null
map.getValue(key)
Returns value or throws
map.entries
Set of key-value pairs
Map with default via getOrPutfun main() {
val cache = mutableMapOf<String, Int>()
val count = cache.getOrPut("hits") { 0 }
cache["hits"] = count + 1
println(cache) // {hits=1}
}
5Collection Operations
Kotlin provides a rich standard library of extension functions on collections — most return new collections without modifying the original (unless using mutable variants like sortInPlace).
Transform and aggregatefun main() {
val numbers = listOf(1, 2, 3, 4, 5)
val doubled = numbers.map { it * 2 }
val sum = numbers.sum()
val avg = numbers.average()
val max = numbers.maxOrNull()
println(doubled) // [2, 4, 6, 8, 10]
println("Sum=$sum, Avg=$avg, Max=$max")
}
Common operations
Operation
Function
Example result
Transform each
map { }
New list of transformed values
Filter
filter { }
Elements matching predicate
Flat map
flatMap { }
Flatten nested collections
Reduce
reduce { acc, x -> }
Single accumulated value
Fold
fold(initial) { acc, x -> }
Reduce with starting value
Group
groupBy { key }
Map of grouped lists
Partition
partition { }
Pair of two lists (match / no match)
Any / All
any { }, all { }
Boolean checks
Take / Drop
take(n), drop(n)
First n or skip first n
groupBy and partitionfun main() {
val words = listOf("apple", "banana", "apricot", "blueberry")
val byFirstLetter = words.groupBy { it.first() }
println(byFirstLetter)
// {a=[apple, apricot], b=[banana, blueberry]}
val (short, long) = words.partition { it.length <= 6 }
println("Short: $short, Long: $long")
}
Lazy sequences: Chain .asSequence() before multiple operations on large collections to avoid intermediate lists — evaluated lazily.
6Iterators
Kotlin collections can be traversed with for loops, forEach, or explicit Iterator objects. Prefer idiomatic Kotlin loops over manual iterators unless you need low-level control.
for loop and forEach
Iterate a listfun main() {
val items = listOf("Kotlin", "Java", "Python")
for (item in items) {
println(item)
}
items.forEach { lang ->
println("Language: $lang")
}
items.forEachIndexed { index, lang ->
println("$index: $lang")
}
}
Explicit Iterator
Iterator and MutableIteratorfun main() {
val list = mutableListOf(1, 2, 3, 4)
val iterator = list.iterator()
while (iterator.hasNext()) {
val value = iterator.next()
if (value % 2 == 0) {
iterator.remove() // safe removal during iteration
}
}
println(list) // [1, 3]
}
Iterating maps
Map iterationfun main() {
val map = mapOf("a" to 1, "b" to 2, "c" to 3)
for (key in map.keys) {
println("Key: $key")
}
for ((key, value) in map) {
println("$key -> $value")
}
map.forEach { (k, v) -> println("$k = $v") }
}
Approach
Best for
for (x in collection)
Simple read-only traversal
forEach { }
Functional style, lambdas
iterator()
Remove while iterating (mutable)
withIndex()
Need index and value together
ranges with indices
for (i in list.indices) gives index range; list[i] accesses element. Use withIndex() when you need both in a forEach.
7Filtering and Sorting
Filtering selects elements matching a condition; sorting arranges elements in a defined order. Kotlin offers both read-only (new list) and in-place (mutable) variants.
Filtering
filter, filterNot, filterIsInstancefun main() {
val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8)
val evens = numbers.filter { it % 2 == 0 }
val odds = numbers.filterNot { it % 2 == 0 }
val greaterThan5 = numbers.filter { it > 5 }
println(evens) // [2, 4, 6, 8]
println(odds) // [1, 3, 5, 7]
println(greaterThan5) // [6, 7, 8]
}
filter on objectsdata class Product(val name: String, val price: Double, val inStock: Boolean)
fun main() {
val products = listOf(
Product("Phone", 999.0, true),
Product("Case", 19.0, false),
Product("Charger", 29.0, true)
)
val available = products.filter { it.inStock }
val affordable = products.filter { it.price < 50 }
println(available.map { it.name }) // [Phone, Charger]
println(affordable.map { it.name }) // [Case, Charger]
}