Kotlin Collections With Examples (Tutorial, Extensions)
Table of Contents
- Introduction
- What Are Kotlin Collections?
- Kotlin Collection Examples
- Types of Collections in Kotlin
- Kotlin Collection Extension Functions
- Count Kotlin Collections
- Advantages of Collections in Kotlin
- Disadvantages of Kotlin Collection
Introduction
In modern software development, data manipulation is at the heart of many applications. Whether you're building a mobile app, a web service, or a desktop application, efficiently managing and processing data is essential. This is where collections come into play, serving as the backbone of data handling in your Kotlin applications.
Kotlin offers a robust and intuitive set of collection classes to simplify data management and manipulation. Understanding how to use Kotlin collections is a crucial skill for any developer looking to write clean, efficient, and maintainable code.
Similar to Java, Kotlin has also introduced collections that are used to store and manipulate a group of objects or data of the same type. These objects in the collection are known as items or elements.
What Are Kotlin Collections?
Kotlin collections are data structures and classes provided by the Kotlin programming language for managing and manipulating groups of elements, such as lists, sets, and maps.
These collections are designed to make it easier for developers to work with data in a structured and efficient manner. Kotlin collections offer a combination of immutability and mutability, allowing developers to choose the appropriate collection type for their specific use case.
Collections are crucial to any programming language, and Kotlin is no exception. Kotlin is known for its rich set of collection that caters to different cases and situations.
We can use other collection types in Kotlin in similar ways, with their specific functions and methods tailored to meet the unique features of each type. Using these collection types, we can seamlessly manage a data group in a Kotlin program.
Kotlin Collection Examples
Here are some examples of Kotlin collections:
1. List:
A list is an ordered collection of elements that allows duplicates. You can access elements by their index.
val fruits = listOf("apple", "banana", "cherry")
println(fruits[1]) // Output: banana
val mutableFruits = mutableListOf("apple", "banana", "cherry")
mutableFruits.add("date")
2. Set:
A set is an unordered collection of unique elements.
val uniqueNumbers = setOf(1, 2, 3, 1, 4)
println(uniqueNumbers) // Output: [1, 2, 3, 4]
val mutableSet = mutableSetOf(1, 2, 3)
mutableSet.add(4)
3. Map:
A map is a collection of key-value pairs. Each key maps to a unique value.
val fruitPrices = mapOf("apple" to 1.0, "banana" to 0.5, "cherry" to 2.0)
println(fruitPrices["banana"]) // Output: 0.5
val mutableMap = mutableMapOf("apple" to 1.0, "banana" to 0.5)
mutableMap["cherry"] = 2.0
Types of Collections in Kotlin
Kotlin collections are categorized into two types:
1. Immutable Collection
The immutable collection supports read-only functionalities, and we can’t alter its elements. The following table showcases immutable collections and their corresponding methods.
-
List
List means an ordered collection that allows us to access elements or items using indices, i.e., integer numbers used to define the position of each element. We can repeat the elements in a list any number of times, but we can’t add or remove operations in the immutable list.
-
Map
It refers to the set of key-value pairs. Keys in the map are unique and can hold just one value for each key. The values of keys can be duplicates, but keys must be unique. We also use maps to store logical connections between two objects. For example, an employee's name and their ID. Considering that the map is immutable, it has a fixed size, and the methods support ready-only access.
-
Set
Set refers to the collection of unordered unique elements that don’t support duplicate elements. Generally, the order of elements in a set collection doesn’t have a significant impact. We are not allowed to add or remove operations, considering that it is an immutable set.
2. Mutable Collection
Mutable collection in Kotlin supports read and write functionalities. The following table shows the mutable collections and their corresponding methods.
-
List
mutableList- It supports read and write operations. We can either add or remove the declared elements in the list.
Array- It is a fixed-sized collection that holds the same type of values. The ArrayList allows us to access elements directly using their indices.
-
Map
MutableMap- MutableMap is a container holding key-value pairs. We can modify both the keys and values after the map is created. It supports functionalities such as put, remove, clear, etc., and we can add, remove, or update key-value pairs.
HashMap- It is an unordered collection of key-value pairs that allows quick access to values based on their keys. However, the order of elements is not guaranteed.
-
Set
MutableSet- The mutable Set supports read and write functionality. It allows us to add or remove elements from the collections easily and preserves the order of the elements.
HashSet- It is an unordered collection of unique elements that don’t allow duplicate elements. In HashSet, the order of elements is not guaranteed.
Kotlin Collection Extension Functions
Kotlin provides a rich set of extensions for working with collections. These extension functions allow you to perform various operations on collections in a concise and expressive manner.
Here are some commonly used Kotlin collection extension functions:
-
map:
Transforms each element in the collection and returns a new collection with the transformed elements.
val numbers = listOf(1, 2, 3, 4, 5)
val squaredNumbers = numbers.map { it * it }
// squaredNumbers contains [1, 4, 9, 16, 25]
-
filter:
Returns a new collection containing only the elements that satisfy a given condition.
val numbers = listOf(1, 2, 3, 4, 5)
val evenNumbers = numbers.filter { it % 2 == 0 }
// evenNumbers contains [2, 4]
-
reduce:
Applies a binary operation to elements in the collection, accumulating a result.
val numbers = listOf(1, 2, 3, 4, 5)
val sum = numbers.reduce { acc, num -> acc + num }
// sum is 15
-
forEach:
Iterates through the collection, applying a given function to each element.
val colors = listOf("red", "green", "blue")
colors.forEach { color ->
println("Color: $color")
}
-
groupBy:
Groups elements in the collection by a specified key or condition, returning a map.
val words = listOf("apple", "banana", "cherry", "date", "elderberry")
val byFirstLetter = words.groupBy { it[0] }
// byFirstLetter is a map with keys "a" and "b," each mapping to a list of words.
-
zip:
Combines two collections into pairs and returns a list of pairs.
val numbers = listOf(1, 2, 3)
val words = listOf("one", "two", "three")
val pairs = numbers.zip(words)
// pairs contains [(1, "one"), (2, "two"), (3, "three")]
-
find:
Returns the first element in the collection that matches a given condition, or null if none match.
val numbers = listOf(1, 2, 3, 4, 5)
val result = numbers.find { it > 2 }
// result is 3
-
distinct:
Returns a collection containing only distinct elements.
val numbers = listOf(1, 2, 2, 3, 3, 4, 5)
val distinctNumbers = numbers.distinct()
// distinctNumbers contains [1, 2, 3, 4, 5]
Count Kotlin Collections
In Kotlin, you can count the number of elements in a collection using the count function. The count function takes a predicate (a condition) as an optional argument and returns the count of elements in the collection that satisfy the given condition. If no predicate is provided, it simply returns the total number of elements in the collection.
Here's how to use the count function:
-
Counting the Total Number of Elements:
val numbers = listOf(1, 2, 3, 4, 5, 2, 3)
val totalElements = numbers.count()
println("Total number of elements: $totalElements") // Output: Total number of elements: 7
-
Counting Elements that Satisfy a Condition:
You can also provide a condition to count specific elements in the collection.
val numbers = listOf(1, 2, 3, 4, 5, 2, 3)
val countEven = numbers.count { it % 2 == 0 }
println("Count of even numbers: $countEven") // Output: Count of even numbers: 3
In the second example, we used a lambda expression as the predicate to count the even numbers in the list.
Advantages of Collections in Kotlin
-
Improved Memory Management
Collections help us avoid manual memory management while enabling the Kotlin runtime to manage the memory.
-
Enhanced Code Readability
Kotlin collections provide a higher-level abstraction to work with data, making code more readable and expressive.
-
Increased Type Safety
Collections make sure that only the correct type of elements are added to it, which increases type safety.
-
Better Efficiency
Kotlin collections allow efficient data storage and retrieval, making them a better option to store large datasets.
Disadvantages of Kotlin Collection
-
Performance Overhead
Collection involves more overhead than working with primitive data types or arrays.
-
Complexity
Collections make code more complex, especially for performing complex operations on the data.
-
Memory Usage
Based on the size and complexity of the collection, it can consume more memory than other data structures.
Depending on the size and complexity of your collections, they can use more memory than other data structures.
Collections are a powerful tool in Kotlin, but it’s important that we use them judiciously based on the program requirements. They are best for times when we need to manage complex or large datasets or perform sophisticated operations on data.