Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Introduction to Collections in Kotlin

What are Collections?

Collections are a fundamental part of programming in Kotlin. They are used to hold multiple values in a single variable. In Kotlin, collections are divided into three main types: Lists, Sets, and Maps. Each of these types serves different purposes and has its own characteristics.

Types of Collections

1. Lists

A List is an ordered collection of items that can contain duplicates. Items in a List can be accessed by their index.

Example:
val fruits = listOf("Apple", "Banana", "Cherry")

You can access elements using their index:

println(fruits[1]) // Output: Banana

2. Sets

A Set is a collection that contains no duplicates. The order of items is not guaranteed.

Example:
val uniqueFruits = setOf("Apple", "Banana", "Apple")

The above Set will only contain two items: Apple and Banana.

3. Maps

A Map is a collection of key-value pairs. Each key must be unique, and it is used to look up values.

Example:
val fruitPrices = mapOf("Apple" to 1.5, "Banana" to 1.2)

You can access a value by its key:

println(fruitPrices["Apple"]) // Output: 1.5

Mutable vs Immutable Collections

Collections in Kotlin can be mutable or immutable. Immutable collections cannot be changed after they are created, while mutable collections can be modified.

Immutable Collection Example:

val numbers = listOf(1, 2, 3)

Attempting to add an element will result in an error.

Mutable Collection Example:

val mutableNumbers = mutableListOf(1, 2, 3)

You can add elements to a mutable collection:

mutableNumbers.add(4) // Now contains 1, 2, 3, 4

Common Operations with Collections

Collections provide various functions to manipulate data, such as adding, removing, and filtering elements.

Filtering Example:

Example:
val evenNumbers = numbers.filter { it % 2 == 0 }

This will return a list of even numbers from the original list.

Conclusion

Collections are essential for data management in Kotlin. Understanding the differences between Lists, Sets, and Maps, as well as mutable and immutable collections, will help you handle data more effectively in your applications.

Whether you're storing a list of items, ensuring uniqueness of data, or mapping keys to values, Kotlin's collection framework provides a powerful and flexible way to manage data.