Kotlin provides a powerful and expressive Collections API that simplifies working with data structures such as lists, sets, and maps. The Collections API offers both mutable and immutable collections, making it easier to manage data efficiently and safely. In this blog, we will explore the Collections API with examples and best practices.
Join our upcoming classes
Our Courses
Kotlin distinguishes between immutable and mutable collections.
Immutable collections: Cannot be modified after creation.
Mutable collections: Can be modified (add, remove, update elements).
Immutable collections are part of Kotlin's standard library and ensure safety in multi-threaded environments.
val numbers: List<Int> = listOf(1, 2, 3, 4, 5)
val names: Set<String> = setOf("Alice", "Bob", "Charlie")
val userAges: Map<String, Int> = mapOf("Alice" to 25, "Bob" to 30)
Mutable collections allow modifications, making them useful for dynamic data structures.
val numbers = mutableListOf(1, 2, 3)
numbers.add(4) // [1, 2, 3, 4]
val names = mutableSetOf("Alice", "Bob")
names.add("Charlie") // [Alice, Bob, Charlie]
val userAges = mutableMapOf("Alice" to 25)
userAges["Bob"] = 30 // {Alice=25, Bob=30}
A List is an ordered collection of elements. It can be either immutable (List
) or mutable (MutableList
).
val fruits = listOf("Apple", "Banana", "Cherry")
println(fruits[0]) // Apple
println(fruits.size) // 3
println(fruits.contains("Banana")) // true
val numbers = mutableListOf(10, 20, 30)
numbers.add(40) // [10, 20, 30, 40]
numbers.remove(20) // [10, 30, 40]
numbers[0] = 100 // [100, 30, 40]
A Set is an unordered collection of unique elements.
val numbers = setOf(1, 2, 3, 3, 4, 5)
println(numbers) // [1, 2, 3, 4, 5] (duplicates removed)
println(numbers.contains(2)) // true
val colors = mutableSetOf("Red", "Blue")
colors.add("Green") // [Red, Blue, Green]
colors.remove("Blue") // [Red, Green]
A Map is a collection of key-value pairs.
val ages = mapOf("Alice" to 25, "Bob" to 30)
println(ages["Alice"]) // 25
println(ages.keys) // [Alice, Bob]
println(ages.values) // [25, 30]
val scores = mutableMapOf("Math" to 90)
scores["Science"] = 85 // {Math=90, Science=85}
scores.remove("Math") // {Science=85}
Kotlin collections support functional programming with built-in higher-order functions.
val numbers = listOf(1, 2, 3, 4, 5)
val evenNumbers = numbers.filter { it % 2 == 0 } // [2, 4]
val squares = numbers.map { it * it } // [1, 4, 9, 16, 25]
val sum = numbers.reduce { acc, num -> acc + num } // 15
val names = listOf("Charlie", "Alice", "Bob")
println(names.sorted()) // [Alice, Bob, Charlie]
println(names.reversed()) // [Bob, Alice, Charlie]
val words = listOf("apple", "banana", "apricot", "blueberry")
val grouped = words.groupBy { it.first() }
println(grouped) // {a=[apple, apricot], b=[banana, blueberry]}
Kotlin also provides advanced collection functions for better data manipulation.
val lists = listOf(listOf(1, 2, 3), listOf(4, 5, 6))
val flatList = lists.flatten()
println(flatList) // [1, 2, 3, 4, 5, 6]
val mapped = lists.flatMap { it.map { num -> num * 2 } }
println(mapped) // [2, 4, 6, 8, 10, 12]
val names = listOf("Alice", "Bob")
val ages = listOf(25, 30)
val paired = names.zip(ages)
println(paired) // [(Alice, 25), (Bob, 30)]
val (unzippedNames, unzippedAges) = paired.unzip()
println(unzippedNames) // [Alice, Bob]
println(unzippedAges) // [25, 30]
The Collections API in Kotlin provides a robust set of tools for handling data efficiently. Understanding lists, sets, maps, and higher-order functions allows developers to write clean, concise, and efficient Kotlin code. Whether you are working with immutable collections for thread safety or mutable collections for dynamic data, Kotlin offers powerful and expressive solutions.
Want to learn more about Kotlin and Jetpack Compose? Stay tuned for more insightful blogs!
Join our upcoming classes
Our Courses
You can connect with me on:
Join our upcoming classes
Our Courses