
Collections in Kotlin
📌 Collections in Kotlin
In Kotlin, Collections are a group of related objects that can be manipulated easily. Collections are broadly categorized into two types:
Immutable Collections → Read-only, cannot be modified. (
List
,Set
,Map
)Mutable Collections → Can be modified (add, remove, or update elements). (
MutableList
,MutableSet
,MutableMap
)
✅ 1. List in Kotlin
A List is an ordered collection of elements. It can contain duplicate elements.
🔎 Immutable List
val numbers = listOf(10, 20, 30, 40, 50)println(numbers) // Output: [10, 20, 30, 40, 50]println(numbers[1]) // Accessing index 1 → Output: 20
🔎 Mutable List
val fruits = mutableListOf("Apple", "Banana", "Cherry")fruits.add("Mango")fruits.remove("Banana")println(fruits) // Output: [Apple, Cherry, Mango]
✅ 2. Set in Kotlin
A Set is an unordered collection that contains unique elements.
🔎 Immutable Set
val setOfNumbers = setOf(1, 2, 3, 4, 4, 5)println(setOfNumbers) // Output: [1, 2, 3, 4, 5]
🔎 Mutable Set
val colors = mutableSetOf("Red", "Blue", "Green")colors.add("Yellow")colors.remove("Blue")println(colors) // Output: [Red, Green, Yellow]
✅ 3. Map in Kotlin
A Map is a collection of key-value pairs. Keys are unique, but values can be duplicated.
🔎 Immutable Map
val countryCode = mapOf("IN" to "India", "US" to "United States", "UK" to "United Kingdom")println(countryCode["IN"]) // Output: India
🔎 Mutable Map
val cityPopulation = mutableMapOf("Delhi" to 18_000_000, "Mumbai" to 20_000_000)cityPopulation["Bangalore"] = 12_000_000cityPopulation.remove("Delhi")println(cityPopulation) // Output: {Mumbai=20000000, Bangalore=12000000}
✅ 4. Common Collection Operations
Function | Description | Example |
---|---|---|
add() | Adds an element to a mutable collection | list.add(100) |
remove() | Removes an element | list.remove(50) |
contains() | Checks if element exists | list.contains(30) → true |
size | Returns the size of the collection | list.size → 5 |
isEmpty() | Checks if collection is empty | list.isEmpty() → false |
indexOf() | Returns the index of an element | list.indexOf(40) → 3 |
filter() | Filters elements based on a condition | list.filter { it > 30 } |
map() | Transforms each element | list.map { it * 2 } |
✅ 5. Example of Collection Operations
val numbers = mutableListOf(1, 2, 3, 4, 5)// Add elementsnumbers.add(6)println(numbers) // [1, 2, 3, 4, 5, 6]// Remove elementnumbers.remove(3)println(numbers) // [1, 2, 4, 5, 6]// Filter elements greater than 4val filteredNumbers = numbers.filter { it > 4 }println(filteredNumbers) // [5, 6]// Map to square of elementsval squaredNumbers = numbers.map { it * it }println(squaredNumbers) // [1, 4, 16, 25, 36]
✅ Conclusion
Use List for ordered data with duplicates.
Use Set for unordered, unique data.
Use Map for key-value pairs.
Kotlin collections offer both immutable and mutable options, making them versatile for data manipulation.