In Kotlin, collections are used to store and manipulate groups of objects. Kotlin provides a rich collection framework through its standard library, offering both read-only (immutable) and modifiable (mutable) collections.
Types of Collections in Kotlin
Collection Name | Description |
|---|---|
Lists | Ordered collections of elements that allow duplicates. |
Sets | Unordered collections of unique elements. |
Maps | Collections of key-value pairs, where each key is unique. |
Arrays | Fixed-size collections of elements with a specific type. |
Sequences | Lazily evaluated collections of elements that can be processed in a pipeline. |
Example:
fun main() {
val fruits = listOf("apple", "banana", "orange", "grape")
println("First fruit: ${fruits[0]}")
println("Last fruit: ${fruits.last()}")
for (fruit in fruits) {
println(fruit)
}
val filtered = fruits.filter { it.startsWith("a") }
println("Filtered list: $filtered")
}
Output
First fruit: apple
Last fruit: grape
apple
banana
orange
grape
Filtered list: [apple]
Explanation:
- listOf() creates an immutable list of fruit names, where elements cannot be added or removed.
- Elements are accessed using index (fruits[0]) and utility functions like last(), and iterated using a for loop.
- The filter() function creates a new list containing only elements that satisfy the given condition (startsWith("a")).
Similar to Java Collections, Kotlin also introduced the concept of collections. A collection usually contains a number of objects of the same type and these objects in the collection are called elements or items. Kotlin Standard Library provides a rich set of tools for managing collections.
Types of Collections
In Kotlin, collections are categorized into two forms.
- Immutable(Read-only) Collection
- Mutable Collection
1. Immutable Collection
Immutable collections in Kotlin are read-only collections, meaning their elements cannot be added, removed, or modified after creation. They help ensure data safety and predictability, especially when shared across different parts of a program. Kotlin provides three main immutable collection types:
- List
- Set
- Map
Immutable List
An immutable list is an ordered collection that allows duplicate elements. Elements can be accessed using their index, but the list cannot be modified once created. It is created using the listOf() function and supports only read operations.
Example
fun main() {
val immutableList = listOf("Ram", "Raj", "Sita")
println(immutableList[0])
for (item in immutableList) {
println(item)
}
}
Output:
Ram
Ram
Raj
Sita
Immutable Set
An immutable set is an unordered collection that stores unique elements only. Duplicate values are automatically removed, and the collection does not support modification. It is created using the setOf() function.
Example
fun main() {
val immutableSet = setOf(6, 9, 9, 0, 0)
for (item in immutableSet) {
println(item)
}
}
Output: (Order may vary)
6
9
0
Immutable Map
Immutable map stores data in key–value pairs, where each key is unique and mapped to exactly one value. The map size and entries cannot be modified after creation. It is created using the mapOf() function and supports read-only access using keys.
Example
fun main() {
val immutableMap = mapOf(1 to "Ram", 2 to "Raj", 3 to "Sita")
for (key in immutableMap.keys) {
println(immutableMap[key])
}
}
Output:
Ram
Raj
Sita
2. Mutable Collection
Mutable collections in Kotlin support both read and write operations. Elements can be added, updated, or removed after the collection is created. These collections are useful when the data needs to change during program execution. Kotlin provides three main mutable collection types:
- MutableList
- MutableSet
- MutableMap
Mutable List
A mutable list is an ordered collection that allows duplicate elements and supports modification operations such as add, remove, and element updates. It is commonly created using the mutableListOf() function.
Example
fun main() {
val mutableList = mutableListOf("Raj", "Ram", "Sita")
mutableList[0] = "Laxman"
mutableList.add("Ravan")
for (item in mutableList) {
println(item)
}
}
Output:
Laxman
Ram
Sita
Ravan
Mutable Set
A mutable set stores unique elements only and supports modification operations like add and remove. Duplicate values are ignored, and element order is not guaranteed. It is created using mutableSetOf().
Example:
fun main() {
val mutableSet = mutableSetOf(6, 10)
mutableSet.add(2)
mutableSet.add(5)
mutableSet.add(6) // duplicate, ignored
for (item in mutableSet) {
println(item)
}
}
Output: (Order may vary)
6
10
2
5
Mutable Map
A mutable map stores data as key–value pairs and allows updating existing values or adding new entries. Keys must be unique, while values can be duplicated. It is commonly created using mutableMapOf().
Example
fun main() {
val mutableMap = mutableMapOf(1 to "Raj", 2 to "Ram", 3 to "Sita")
mutableMap[1] = "Laxman"
mutableMap[4] = "Ravan"
for (value in mutableMap.values) {
println(value)
}
}
Output:
Laxman
Ram
Sita
Ravan