Sling Academy
Home/Kotlin/Introduction to Collections in Kotlin

Introduction to Collections in Kotlin

Last updated: November 30, 2024

In Kotlin, collections play a crucial role in storing, retrieving, and managing groups of related objects or values. Understanding how collections work in Kotlin will enable you to work with data more effectively, providing both functionality and flexibility to your programs.

Types of Collections in Kotlin

Kotlin provides several powerful collection types, including:

  • List: An ordered collection that can contain duplicate elements. Elements in lists can typically be accessed using indices.
  • Set: A collection of unique elements. Sets do not allow duplicate elements.
  • Map: A collection of key-value pairs where each key is unique. Maps allow efficient data retrieval using the key.

List

In Kotlin, lists are a great way to store ordered collections of elements. You can create mutable lists (with mutableListOf) or read-only lists (with listOf).

// Kotlin Code for List
val readOnlyList = listOf("Apple", "Banana", "Cherry")
val mutableList = mutableListOf("Apple", "Banana", "Cherry")

// Access elements
println(readOnlyList[1]) // Output: Banana

// Modify a mutable list
mutableList[0] = "Apricot"
println(mutableList) // Output: [Apricot, Banana, Cherry]

Set

Kotlin sets are collections that ensure there are no duplicate elements. You can use setOf for read-only sets and mutableSetOf for mutable ones.

// Kotlin Code for Set
val readOnlySet = setOf("Apple", "Banana", "Cherry", "Apple")
val mutableSet = mutableSetOf("Apple", "Banana", "Cherry")

// Sets automatically ignore duplicate entries
println(readOnlySet) // Output: [Apple, Banana, Cherry]

// Add a new element to the mutable set
mutableSet.add("Apricot")
println(mutableSet) // Output: [Apple, Banana, Cherry, Apricot]

Map

Maps are particularly useful when you need to associate keys with values. You can invoke mapOf to create a read-only map, or mutableMapOf for a mutable version.

// Kotlin Code for Map
val readOnlyMap = mapOf("Apple" to 1.29, "Banana" to 0.79)
val mutableMap = mutableMapOf("Apple" to 1.29, "Banana" to 0.79)

// Access a value
println(readOnlyMap["Apple"]) // Output: 1.29

// Add a new key-value pair to the mutable map
mutableMap["Cherry"] = 2.49
println(mutableMap) // Output: {Apple=1.29, Banana=0.79, Cherry=2.49}

Transformations and Filtering

Kotlin collections provide a range of operations for transforming and filtering data efficiently.

// Kotlin Code for Transformations and Filtering
val numbers = listOf(1, 2, 3, 4, 5, 6)

// Filter even numbers
val evenNumbers = numbers.filter { it % 2 == 0 }
println(evenNumbers) // Output: [2, 4, 6]

// Map to squares of numbers
val squaredNumbers = numbers.map { it * it }
println(squaredNumbers) // Output: [1, 4, 9, 16, 25, 36]

Conclusion

Collections in Kotlin are integral to writing concise and efficient code, making it easier to manipulate large sets of data. By mastering lists, sets, and maps, along with their operations, you can develop more effective Kotlin programs.

Next Article: Kotlin Immutable vs Mutable Collections: Key Differences

Series: Kotlin Collections

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin