Collections in Kotlin - Lists, Sets, and Maps


Collections are fundamental data structures in Kotlin, and they play a significant role in many applications. In this guide, we'll explore how to work with lists, sets, and maps in Kotlin.


Lists

A list is an ordered collection of elements. In Kotlin, you can create a list using the `listOf()` function:

val numbers = listOf(1, 2, 3, 4, 5)
println("List: $numbers")

Sets

A set is an unordered collection of unique elements. You can create a set using the `setOf()` function:

val uniqueNumbers = setOf(1, 2, 3, 4, 5, 5)
println("Set: $uniqueNumbers")

Maps

A map is a collection of key-value pairs. In Kotlin, you can create a map using the `mapOf()` function:

val personInfo = mapOf("name" to "Alice", "age" to 30, "city" to "Wonderland")
println("Map: $personInfo")

Working with Collections

Kotlin provides various functions for working with collections, such as filtering, mapping, and transforming:

val numbers = listOf(1, 2, 3, 4, 5)
// Filtering
val evenNumbers = numbers.filter { it % 2 == 0 }
// Mapping
val squaredNumbers = numbers.map { it * it }
// Reducing
val sum = numbers.reduce { acc, num -> acc + num }

Mutable Collections

If you need to modify a collection, use a mutable variant like `mutableListOf()`, `mutableSetOf()`, or `mutableMapOf()`. These allow you to add and remove elements:

val mutableList = mutableListOf(1, 2, 3)
mutableList.add(4)
mutableList.remove(2)
println("Mutable List: $mutableList")

Conclusion

Collections are essential for managing data in Kotlin. Whether you're dealing with lists of items, sets of unique values, or maps with key-value pairs, Kotlin's standard library provides a rich set of functions for handling collections efficiently. Understanding and using collections effectively is a key skill for Kotlin developers.


Happy coding!