Kotlin collections.
We learned about collections conceptually. Now we see how Kotlin implements them. Lists, sets, maps. Mutable and immutable. Powerful operations. Today we master Kotlin's collection types and their operations.
Kotlin has three main collection types.
List: ordered collection with duplicates allowed. Access by index. First, second, third element.
Set: unordered collection with no duplicates. Membership matters. Is this element present?
Map: key-value pairs. Look up values by key. Like a dictionary.
Each has two variants: read-only and mutable.
Read-only: you can read but not modify. List, Set, Map.
Mutable: you can add, remove, and modify. MutableList, MutableSet, MutableMap.
Read-only is the default. Prefer immutability unless you need to modify.
Create lists with listOf: val numbers equals listOf 1, 2, 3.
Create mutable lists with mutableListOf: val mutableNumbers equals mutableListOf 1, 2, 3.
Create sets with setOf: val uniqueNames equals setOf "Alice", "Bob".
Create maps with mapOf: val ages equals mapOf "Alice" to 30, "Bob" to 25.
Empty collections: emptyList, emptySet, emptyMap.
The to keyword creates pairs for maps. It is shorthand for Pair "Alice", 30.
Type inference works. listOf 1, 2, 3 is List of Int. The compiler knows.
Access elements by index: list bracket 0 or list dot get 0.
First and last: list dot first, list dot last. Safe versions: firstOrNull, lastOrNull.
Size: list dot size. Is it empty: list dot isEmpty.
Contains: list dot contains element or element in list.
Find: list dot find with condition returns first match or null.
Index: list dot indexOf element returns position or minus 1.
Sublists: list dot subList 0, 3 or list dot take 3.
For mutable lists: add, remove, clear, set.
Sets focus on membership, not order.
Create: val set equals setOf 1, 2, 3, 2. Result has no duplicate 2.
Check membership: element in set. Fast lookup.
Set operations: union to combine, intersect for common, subtract for difference.
setA union setB gives all elements from both.
setA intersect setB gives elements in both.
setA subtract setB gives elements in A but not B.
For mutable sets: add, remove, clear.
Maps store key-value pairs.
Access: map bracket key or map dot get key. Returns null if key not found.
Safe access: map dot getOrDefault key, default.
Keys and values: map dot keys gives all keys. map dot values gives all values.
Entries: map dot entries gives key-value pairs.
Contains: key in map or map dot containsKey key. map dot containsValue value.
For mutable maps: put key, value, remove key, clear.
Shorthand: map bracket key equals value for put.
filter keeps elements matching a condition.
val evens equals numbers dot filter open brace it mod 2 equals 0 close brace.
map transforms each element.
val doubled equals numbers dot map open brace it times 2 close brace.
These are the most common collection operations. They work on lists, sets, and other iterables.
Chain them: numbers dot filter open brace it greater than 0 close brace dot map open brace it times 2 close brace.
filter produces a smaller or equal collection. map produces a collection of the same size.
Both return new collections. The original is unchanged.
flatMap: transform and flatten. Each element becomes a list, all lists combined.
val nested equals listOf listOf 1, 2, listOf 3, 4. nested dot flatten gives listOf 1, 2, 3, 4.
groupBy: group elements by a key.
people dot groupBy open brace it dot city close brace gives Map of String to List of Person.
associate: create a map from elements.
people dot associateBy open brace it dot id close brace gives Map of Long to Person.
partition: split into two lists based on condition.
val evens and odds equals numbers dot partition open brace it mod 2 equals 0 close brace.
reduce: combine all elements into one.
numbers dot reduce open brace acc, n arrow acc plus n close brace gives the sum.
fold: like reduce but with an initial value.
numbers dot fold 0 open brace acc, n arrow acc plus n close brace also gives the sum.
Use fold when the result type differs from element type.
Shortcuts: sum, count, average, max, min.
numbers dot sum is cleaner than reduce for addition.
first with condition, last with condition find specific elements.
Destructuring extracts components.
For pairs: val key and value equals pair.
For lists: val first, second, third equals listOf 1, 2, 3.
In loops: for key and value in map, use both.
Data classes support destructuring: val name and age equals person.
Destructuring makes code cleaner when working with structured data.
Use underscore to skip: val name and underscore equals pair. Ignore the second component.
Let us summarize.
List, Set, Map are Kotlin's main collection types.
Read-only by default. Use mutable variants when needed.
Create with listOf, setOf, mapOf. Mutable with mutableListOf, etc.
filter selects elements. map transforms elements.
flatMap, groupBy, associate for complex transformations.
reduce and fold combine elements into one result.
Destructuring extracts components from pairs, lists, and data classes.
Collections are fundamental to Kotlin programming.