Kotlin Collections – Working with Lists, Sets, and Maps

Introduction

Collections are a crucial part of any programming language as they allow you to store, access, and manipulate groups of related objects. Kotlin offers a wide variety of collection types like lists, sets, and maps, making it easier to work with data structures.

In this post, you’ll learn:
Kotlin Lists
Kotlin Sets
Kotlin Maps
Operations on Collections
Best Practices for Using Collections in Kotlin

By the end of this post, you’ll be equipped with the knowledge to effectively work with Kotlin’s collection types!


1. Kotlin Lists

A list is an ordered collection that allows duplicate elements. Kotlin provides two main types of lists: mutable lists and immutable lists. An immutable list cannot be modified once it’s created, while a mutable list allows adding, removing, or updating elements.

Immutable Lists

To create an immutable list, you use listOf().

kotlinCopyEditval fruits = listOf("Apple", "Banana", "Cherry")
println(fruits) // Output: [Apple, Banana, Cherry]

Mutable Lists

For a mutable list, you use mutableListOf(), which allows modification of elements.

kotlinCopyEditval numbers = mutableListOf(1, 2, 3, 4)
numbers.add(5)    // Adding an element
numbers.remove(2) // Removing an element
println(numbers)  // Output: [1, 3, 4, 5]

Accessing List Elements

You can access list elements by index or use various functions to work with the list.

kotlinCopyEditprintln(fruits[0])  // Output: Apple
println(fruits.first()) // Output: Apple
println(fruits.last())  // Output: Cherry

2. Kotlin Sets

A set is a collection that does not allow duplicate elements, and it doesn’t maintain any specific order. Kotlin provides immutable sets and mutable sets.

Immutable Sets

You can create an immutable set with setOf().

kotlinCopyEditval numbersSet = setOf(1, 2, 3, 4)
println(numbersSet) // Output: [1, 2, 3, 4]

Mutable Sets

For a mutable set, you use mutableSetOf(). You can add and remove elements.

kotlinCopyEditval colors = mutableSetOf("Red", "Green", "Blue")
colors.add("Yellow")    // Adding an element
colors.remove("Green")  // Removing an element
println(colors)         // Output: [Red, Blue, Yellow]

Set Operations

Sets support common operations such as union, intersection, and difference:

kotlinCopyEditval set1 = setOf(1, 2, 3)
val set2 = setOf(2, 3, 4)

println(set1.union(set2))    // Output: [1, 2, 3, 4]
println(set1.intersect(set2)) // Output: [2, 3]
println(set1.subtract(set2))  // Output: [1]

3. Kotlin Maps

A map is a collection that holds key-value pairs, where each key is unique. Kotlin offers immutable maps and mutable maps.

Immutable Maps

To create an immutable map, you use mapOf().

kotlinCopyEditval countryCapitals = mapOf("USA" to "Washington, D.C.", "Canada" to "Ottawa")
println(countryCapitals) // Output: {USA=Washington, D.C., Canada=Ottawa}

Mutable Maps

For a mutable map, you use mutableMapOf(). You can add, remove, or modify key-value pairs.

kotlinCopyEditval studentGrades = mutableMapOf("John" to "A", "Jane" to "B")
studentGrades["John"] = "A+"   // Updating a value
studentGrades["Mark"] = "C"    // Adding a new key-value pair
studentGrades.remove("Jane")   // Removing a key-value pair
println(studentGrades)         // Output: {John=A+, Mark=C}

Accessing Map Elements

You can access map values using their keys.

kotlinCopyEditprintln(countryCapitals["USA"]) // Output: Washington, D.C.
println(studentGrades.getOrDefault("Sarah", "N/A")) // Output: N/A

4. Operations on Collections

Kotlin collections come with several useful operations to manipulate the data within. These include methods like filter(), map(), reduce(), and forEach().

Filtering Collections

The filter() method creates a new collection containing only the elements that match the provided condition.

kotlinCopyEditval numbers = listOf(1, 2, 3, 4, 5)
val evenNumbers = numbers.filter { it % 2 == 0 }
println(evenNumbers) // Output: [2, 4]

Mapping Collections

The map() function transforms each element in a collection based on a provided transformation.

kotlinCopyEditval numbers = listOf(1, 2, 3)
val squaredNumbers = numbers.map { it * it }
println(squaredNumbers) // Output: [1, 4, 9]

Reducing Collections

The reduce() function combines the elements of a collection into a single result using a provided operation.

kotlinCopyEditval numbers = listOf(1, 2, 3, 4)
val sum = numbers.reduce { acc, num -> acc + num }
println(sum) // Output: 10

For Each Collection

The forEach() method iterates through each element in a collection.

kotlinCopyEditval fruits = listOf("Apple", "Banana", "Cherry")
fruits.forEach { println(it) }
// Output:
// Apple
// Banana
// Cherry

5. Best Practices for Using Collections in Kotlin

Here are some best practices to help you work efficiently with Kotlin collections:
Choose the right collection type: Use lists for ordered data, sets for unique elements, and maps for key-value pairs.
Use immutable collections: Prefer immutable collections to avoid unintentional side effects. Immutable collections can also help prevent bugs in concurrent applications.
Avoid unnecessary boxing: Kotlin supports primitive types like Int, Float, and Double, so avoid unnecessary conversion to boxed types like Integer, Double, etc.
Use higher-order functions: Leverage Kotlin’s built-in functions like map(), filter(), and reduce() to write concise and expressive code.
Handle null safely: Use Kotlin’s null safety features, such as getOrElse(), getOrNull(), and the safe call operator ?. to avoid NullPointerException.


Conclusion

In this post, you learned:
✅ The difference between immutable and mutable lists, sets, and maps.
✅ How to perform basic operations on collections, like filtering, mapping, and reducing.
✅ Best practices for using Kotlin collections effectively.

🎯 Next Post: Kotlin Lambdas and Functional Programming

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *