Kotlin Collections

Lists, sets, maps, iterators, and powerful collection operations for filtering and sorting

List Set Map filter

Table of Contents

1Lists

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

FunctionTypeDescription
listOf(...)List (read-only)Fixed elements, immutable view
emptyList()ListEmpty read-only list
List(n) { index -> ... }ListBuild 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.

mutableListOffun main() { val tasks = mutableListOf("Learn Kotlin", "Build app") tasks.add("Publish app") tasks.add(1, "Practice collections") tasks.remove("Learn Kotlin") tasks[0] = "Master Kotlin" println(tasks) // [Master Kotlin, Practice collections, Publish app] }

Key mutable operations

MethodAction
add(element)Append to end
add(index, element)Insert at index
remove(element)Remove first match
removeAt(index)Remove by index
set(index, element) or list[i] = xReplace element
clear()Remove all elements
ArrayList and LinkedListfun main() { val arrayList: MutableList<Int> = arrayListOf(1, 2, 3) val linkedList: MutableList<Int> = linkedListOf(1, 2, 3) arrayList.add(4) linkedList.addFirst(0) // Kotlin 1.4+ extension println(arrayList) // [1, 2, 3, 4] println(linkedList) // [0, 1, 2, 3] }
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

FunctionImplementationNotes
setOf(...)LinkedHashSetRead-only, insertion order
mutableSetOf(...)LinkedHashSetMutable, insertion order
hashSetOf(...)HashSetMutable, no guaranteed order
sortedSetOf(...)TreeSetMutable, 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 / syntaxDescription
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.entriesSet 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

OperationFunctionExample result
Transform eachmap { }New list of transformed values
Filterfilter { }Elements matching predicate
Flat mapflatMap { }Flatten nested collections
Reducereduce { acc, x -> }Single accumulated value
Foldfold(initial) { acc, x -> }Reduce with starting value
GroupgroupBy { key }Map of grouped lists
Partitionpartition { }Pair of two lists (match / no match)
Any / Allany { }, all { }Boolean checks
Take / Droptake(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") } }
ApproachBest 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] }

Sorting

sorted, sortedBy, sortedDescendingfun main() { val names = listOf("Charlie", "Alice", "Bob") println(names.sorted()) // [Alice, Bob, Charlie] println(names.sortedDescending()) // [Charlie, Bob, Alice] println(names.sortedBy { it.length }) // by length val mutable = names.toMutableList() mutable.sort() // in-place sort println(mutable) }
sortBy and compareBydata class Student(val name: String, val grade: Int) fun main() { val students = listOf( Student("Nikhil", 85), Student("Alex", 92), Student("Sam", 78) ) val byGrade = students.sortedByDescending { it.grade } val byNameThenGrade = students.sortedWith( compareBy<Student>({ it.name }, { it.grade }) ) byGrade.forEach { println("${it.name}: ${it.grade}") } }

Filter + sort pipeline

Chained operationsfun main() { val scores = listOf(45, 88, 92, 67, 95, 54, 91) val topPassing = scores .filter { it >= 60 } .sortedDescending() .take(3) println(topPassing) // [95, 92, 91] }
TaskRead-only (new list)In-place (mutable)
Filterfilter { }removeAll { }
Sort ascendingsorted()sort()
Sort descendingsortedDescending()sortDescending()
Sort by propertysortedBy { }sortBy { }
Learn more

Filtering and sorting use lambdas — covered in depth in Lambda & Higher-Order Functions.

8Summary Cheatsheet

TopicKey Takeaway
ListslistOf — ordered, duplicates OK, read-only
Mutable ListsmutableListOf — add, remove, update
SetssetOf / mutableSetOf — unique elements
MapsmapOf, key to value, map[key]
Operationsmap, filter, groupBy, fold, partition
Iteratorsfor, forEach, iterator() for safe remove
Filter & Sortfilter { }, sorted(), sortedBy { }
Next lessonLambda & Higher-Order Functions

Kotlin Collections MCQ Practice

10 Basic MCQs 10 Advanced MCQs

10 Basic Kotlin Collections MCQs

1

listOf creates?

AMutable list
BRead-only list interface
CSet
DMap
Explanation: See Kotlin Collections lesson — correct answer is B.
2

mutableListOf creates?

AImmutable list
BMutable list you can add/remove from
CArray only
DMap
Explanation: See Kotlin Collections lesson — correct answer is A.
3

Set collection property?

AAllows duplicates
BNo duplicate elements
CKey-value pairs
DSorted always
Explanation: See Kotlin Collections lesson — correct answer is B.
4

mapOf creates?

AList
BRead-only Map
CMutable map always
DSet
Explanation: See Kotlin Collections lesson — correct answer is A.
5

Pair creation idiomatic syntax?

APair(a,b) only
B"key" to value
CMap.pair
Djoin()
Explanation: See Kotlin Collections lesson — correct answer is B.
6

Access first list element?

Alist.first() or list[0]
Blist.head()
Clist.getFirst() only
Dlist(0)
Explanation: See Kotlin Collections lesson — correct answer is A.
7

filter returns?

ASame mutable list
BNew list with matching elements
CUnit
DBoolean
Explanation: See Kotlin Collections lesson — correct answer is B.
8

map (collection) transforms?

AEach element to new value in new list
BSorts in place
CRemoves duplicates
DConverts to Set only
Explanation: See Kotlin Collections lesson — correct answer is A.
9

forEach is for?

ABuilding new list
BSide effects on each element
CSorting
DGrouping only
Explanation: See Kotlin Collections lesson — correct answer is B.
10

Map keys accessed via?

Amap.keys or map[key]
Bmap.list()
Cmap.first
Dmap.entries only illegal
Explanation: See Kotlin Collections lesson — correct answer is A.

10 Advanced Kotlin Collections MCQs

11

groupBy returns?

AList
BMap of keys to lists of elements
CSet
DSingle value
Explanation: See Kotlin Collections lesson — correct answer is B.
12

distinct returns?

ASorted list
BList with duplicates removed
CMutable copy
DMap
Explanation: See Kotlin Collections lesson — correct answer is A.
13

flatMap combines?

Amap then flatten nested collections
BOnly sort
COnly filter
DSet union
Explanation: See Kotlin Collections lesson — correct answer is B.
14

Read-only List from mutableList?

ACan never add via any reference
BRead-only view may still mutate if backing list changes
CAlways copied
DThrows always
Explanation: See Kotlin Collections lesson — correct answer is A.
15

associate creates?

AList
BMap from collection
CSet
DArray
Explanation: See Kotlin Collections lesson — correct answer is B.
16

sortedBy returns?

AMutates original
BNew sorted list by key selector
CSet
DMap
Explanation: See Kotlin Collections lesson — correct answer is A.
17

contains and in operator?

ADifferent for lists
Bin checks membership like contains
Cin only for maps
Dcontains only strings
Explanation: See Kotlin Collections lesson — correct answer is B.
18

sumOf used for?

ASum after mapping each element
BString concat only
CSort
DFilter
Explanation: See Kotlin Collections lesson — correct answer is A.
19

emptyList() vs listOf()

AIdentical immutable empty list
BDifferent types always
CemptyList mutable
DlistOf null only
Explanation: See Kotlin Collections lesson — correct answer is B.
20

Iterator allows?

AOnly read via for loop
BSequential access; MutableIterator also remove
CRandom access only
DSort in place
Explanation: See Kotlin Collections lesson — correct answer is A.
Click an option to select, then check answers.

Kotlin Collections Interview Q&A

15 topic-focused questions for interviews and revision.

1Difference between List and MutableList?easy
Answer: List is read-only interface — no add/remove. MutableList extends with modification operations like add and remove.
2How create immutable vs mutable list?easy
Answer: listOf(1,2,3) read-only; mutableListOf(1,2,3) can be modified.
3What is a Map?easy
Answer: Key-value collection — mapOf("a" to 1); access with map[key] returning nullable value.
4What is a Set?easy
Answer: Collection with unique elements — setOf(1,2,2) gives {1,2}.
5Explain filter and map.medium
Answer: filter keeps elements matching predicate; map transforms each element to new value — both return new lists.
6What is groupBy?medium
Answer: list.groupBy { it.category } — produces Map> grouping elements by key function.
7Read-only vs mutable collection views?medium
Answer: Read-only interface prevents modification through that reference; backing collection may still change if another mutable reference exists.
8Pair and destructuring?medium
Answer: val (name, score) = "Alex" to 95 — Pair destructuring or use component1/component2.
9Difference between forEach and map?medium
Answer: forEach runs action for side effects (returns Unit). map transforms to new collection.
10How sort a list?medium
Answer: sorted(), sortedBy { it.name }, sortedDescending() — return new lists; sort() mutates mutable list in place.
11flatMap vs map?hard
Answer: map: one output per element. flatMap: map each to collection then flatten — e.g. words from sentences.
12associate vs associateBy?hard
Answer: associate { it.id to it } builds map from pairs; associateBy { it.id } uses key selector with element as value.
13When use Sequence instead of List?hard
Answer: Sequence lazy evaluation for long chains — avoids intermediate lists; good for large data or infinite streams.
14Collection immutability best practice?hard
Answer: Expose List from API, use mutableList internally — prevents callers from modifying internal state.
15fold vs reduce?hard
Answer: fold has initial accumulator value; reduce uses first element as initial — both aggregate collection to single value.