Kotlin Tutorial
Estimated reading: 3 minutes 26 views

📊 Kotlin Arrays & Collections – Lists, Sets, Maps & Iteration Essentials

🧲 Introduction – Store, Access & Manage Data with Kotlin Collections

Collections are essential in any programming language for handling groups of data. Kotlin provides a rich set of collection types including arrays, lists, sets, and maps—each available in immutable and mutable forms.

Kotlin collections are optimized for performance and safety, integrating seamlessly with functional programming features like lambdas and forEach, and offering null safety through built-in tools.

🎯 In this guide, you’ll learn:

  • How to declare and access arrays in Kotlin
  • The differences between lists, sets, and maps (mutable vs immutable)
  • How to use collection methods like filter, map, and forEach
  • Best practices for manipulating key-value pairs and unique sets

📘 Topics Covered

📦 Topic📖 Description
🧮 Kotlin – ArraysCreating and accessing fixed-size, indexed arrays.
📚 Kotlin – Collections OverviewIntroduction to Kotlin’s unified collection framework.
📋 Kotlin – ListsOrdered collections that allow duplicates; mutable and immutable versions.
🔢 Kotlin – SetsUnordered collections that contain unique elements only.
🗺️ Kotlin – MapsKey-value pairs for fast data lookups; available as mutable and immutable.

🔍 Detailed Sections & Examples

🧮 Kotlin – Arrays

val numbers = arrayOf(1, 2, 3, 4)
println(numbers[0])        // Output: 1
println(numbers.size)      // Output: 4

🧠 Arrays are fixed-size collections accessible via index.

✅ Update values:

numbers[1] = 10

📚 Kotlin – Collections Overview

Kotlin offers two collection types:

TypeMutable?Example Types
ImmutableNolistOf(), setOf(), mapOf()
MutableYesmutableListOf(), mutableSetOf(), mutableMapOf()

🔍 Immutable collections cannot be modified after creation, promoting safety and immutability in code.


📋 Kotlin – Lists (Mutable & Immutable)

val fruits = listOf("Apple", "Banana", "Cherry")  // Immutable
val numbers = mutableListOf(1, 2, 3)              // Mutable

numbers.add(4)
println(numbers)  // Output: [1, 2, 3, 4]

✅ Lists maintain order and can contain duplicates.

📌 Access elements by index: fruits[0]"Apple"


🔢 Kotlin – Sets (Mutable & Immutable)

val items = setOf("A", "B", "C", "A")      // Duplicates are removed
val mutableItems = mutableSetOf("X", "Y")
mutableItems.add("Z")

💡 Sets store unique values only and do not preserve order.

✅ Useful when checking for presence or removing duplicates.


🗺️ Kotlin – Maps (Key-Value Pairs)

val userMap = mapOf("name" to "Alice", "age" to 30)
val mutableUserMap = mutableMapOf("id" to 101)

println(userMap["name"])  // Output: Alice

mutableUserMap["location"] = "India"

📌 Maps associate keys with values and provide fast access.

🧠 Use to keyword to define key-value pairs.


📌 Summary – Recap & Next Steps

Kotlin’s collections give you the tools to handle lists, sets, and maps effectively—both in immutable and mutable forms. Understanding how and when to use each type helps you write cleaner, safer, and more flexible code.

🔍 Key Takeaways:

  • Arrays are fixed-size; lists and other collections are more flexible.
  • Lists are ordered and allow duplicates; sets store only unique items.
  • Maps pair keys with values for fast lookups.
  • Choose immutable versions for safety and mutable for flexibility.

⚙️ Practical Use Cases:

  • Managing dynamic lists in Android apps (e.g., to-do items)
  • Removing duplicates from a set of user entries
  • Building configurations or lookup tables with maps

❓ Frequently Asked Questions

What’s the difference between arrayOf() and listOf() in Kotlin?
arrayOf() creates a fixed-size array, while listOf() creates an immutable list.


Can I convert between immutable and mutable collections?
✅ Yes. Use .toMutableList() or .toList():

val mutable = listOf(1, 2).toMutableList()

Are Kotlin collections thread-safe?
✅ By default, no. Use synchronized wrappers or thread-safe alternatives like ConcurrentHashMap if needed.


How do I iterate over a map in Kotlin?
✅ Use for ((key, value) in map):

for ((k, v) in userMap) {
    println("$k -> $v")
}

Do sets maintain order in Kotlin?
✅ No. setOf() and mutableSetOf() are unordered. Use LinkedHashSet if order matters.


Share Now :

Leave a Reply

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

Share

Kotlin Arrays & Collections

Or Copy Link

CONTENTS
Scroll to Top