Kotlin Collection Operations 🎯

beginner
23 min

Kotlin Collection Operations 🎯

Welcome to our deep dive into Kotlin Collection Operations! In this comprehensive guide, we'll explore the essential tools for managing collections in your Kotlin projects. 📝

Collections are a crucial part of programming, allowing us to store, manipulate, and access data efficiently. Kotlin provides a wide array of collection types and operations to help you tackle real-world problems with ease.

Let's start with the basics.

Collection Types in Kotlin 📝

Kotlin has four primary collection types:

  1. Lists (List<T>): Ordered, duplicates allowed, can be mutable (MutableList<T>) or immutable (List<T>).
  2. Sets (Set<T>): Unordered, no duplicates allowed, can be mutable (MutableSet<T>) or immutable (Set<T>).
  3. Maps (Map<K, V>): Key-value pairs, no duplicates allowed for keys, can be mutable (MutableMap<K, V>) or immutable (Map<K, V>).
  4. Arrays (Array<T>): Ordered, duplicates allowed, fixed size, cannot be resized.

Accessing and Manipulating Collections 💡

Now that we've covered the basic collection types, let's dive into some practical operations we can perform on them.

Accessing Elements

To access an element in a collection, you can use the [] operator.

kotlin
val list = listOf(1, 2, 3, 4, 5) val firstElement = list[0] // Accessing the first element

Adding and Removing Elements

For mutable collections, you can add and remove elements using the add(), remove(), and clear() functions.

kotlin
val mutableList = mutableListOf(1, 2, 3, 4, 5) mutableList.add(6) // Adding an element mutableList.removeAt(2) // Removing the element at index 2 mutableList.clear() // Clearing the entire list

Iterating Over Collections

You can iterate over collections using a for-loop or the forEach() function.

kotlin
val list = listOf(1, 2, 3, 4, 5) for (element in list) { println(element) } list.forEach { println(it) }

Advanced Collection Operations 💡

Kotlin provides several advanced operations like filtering, sorting, and transforming collections.

Filtering Collections

You can filter a collection using the filter() function.

kotlin
val numbers = listOf(1, 2, 3, 4, 5) val evenNumbers = numbers.filter { it % 2 == 0 }

Sorting Collections

To sort a collection, use the sort() function.

kotlin
val numbers = listOf(5, 3, 1, 4, 2) numbers.sort()

Transforming Collections

You can transform a collection using the map() function.

kotlin
val numbers = listOf(1, 2, 3, 4, 5) val squares = numbers.map { it * it }

Quiz 📝

Quick Quiz
Question 1 of 1

Which function is used to sort a mutable list in Kotlin?

Remember, practice makes perfect! As you continue learning Kotlin, keep exploring and experimenting with these collection operations to build powerful and efficient applications. Happy coding! 💡