Collections API in Kotlin with Examples

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


1. Immutable vs Mutable Collections

Kotlin distinguishes between immutable and mutable collections.

  • Immutable collections: Cannot be modified after creation.

  • Mutable collections: Can be modified (add, remove, update elements).

Creating Immutable Collections

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)

Creating Mutable Collections

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}

2. List in Kotlin

A List is an ordered collection of elements. It can be either immutable (List) or mutable (MutableList).

Common List Operations

val fruits = listOf("Apple", "Banana", "Cherry")
println(fruits[0]) // Apple
println(fruits.size) // 3
println(fruits.contains("Banana")) // true

Modifying a MutableList

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]

3. Set in Kotlin

A Set is an unordered collection of unique elements.

Common Set Operations

val numbers = setOf(1, 2, 3, 3, 4, 5)
println(numbers) // [1, 2, 3, 4, 5] (duplicates removed)
println(numbers.contains(2)) // true

Modifying a MutableSet

val colors = mutableSetOf("Red", "Blue")
colors.add("Green") // [Red, Blue, Green]
colors.remove("Blue") // [Red, Green]

4. Map in Kotlin

A Map is a collection of key-value pairs.

Common Map Operations

val ages = mapOf("Alice" to 25, "Bob" to 30)
println(ages["Alice"]) // 25
println(ages.keys) // [Alice, Bob]
println(ages.values) // [25, 30]

Modifying a MutableMap

val scores = mutableMapOf("Math" to 90)
scores["Science"] = 85 // {Math=90, Science=85}
scores.remove("Math") // {Science=85}

5. Higher-Order Functions in Collections

Kotlin collections support functional programming with built-in higher-order functions.

Filter, Map, and Reduce

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

Sorting and Reversing

val names = listOf("Charlie", "Alice", "Bob")
println(names.sorted()) // [Alice, Bob, Charlie]
println(names.reversed()) // [Bob, Alice, Charlie]

Grouping and Chunking

val words = listOf("apple", "banana", "apricot", "blueberry")
val grouped = words.groupBy { it.first() }
println(grouped) // {a=[apple, apricot], b=[banana, blueberry]}

6. Advanced Collection Operations

Kotlin also provides advanced collection functions for better data manipulation.

FlatMap and Flatten

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]

Zip and Unzip

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]

Conclusion

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


Akshay Nandwana
Founder
AndroidEngineers

You can connect with me on:


Book 1:1 Session here
Click Here

Join our upcoming classes
Our Courses

Love from our past students

Excellent list of questions really helped me to coverup all the topics before interview.

Saiteja Janjirala

10th Oct, 2024

I had an exceptional experience with the 1:1 mentorship session. Akshay was incredibly friendly and provided invaluable guidance on focusing on long-term goals. They also gave great interview tips, including a thorough resume review. Additionally, the discussion on Data Structures and Algorithms (DSA) was insightful and practical. Highly recommended for anyone looking to advance their career!

Nayab khan

11th Sep, 2024

Cleared my major points for what I am missing in the resume and also suggested what I can work on for further growth in the career.

Ketan Chaurasiya

7th Aug, 2024

What impressed me most was his personalized approach and practical tips that I could immediately apply. Akshay’s guidance not only improved my technical skills but also boosted my confidence in navigating my career path. His insights and encouragement have been a game-changer for me. I highly recommend Akshay’s mentorship to anyone looking to advance their Android development career.

Hardik Kubavat

5th Aug, 2024

2025© Made with   by Android Engineers.