In addition to the relatively rigid data structures such as arrays, Kotlin also uses other much more flexible data constructs - the so-called Collections. Kotlin Collections are generic data structures used to store and manage a group of objects of the same type. They offer a variety of methods and functions to access, manipulate, add or remove the stored items.
Collections are not a specialty or invention of Kotlin, but a fundamental concept in many programming languages. Java provides a Collection API, which consists of numerous interfaces and classes to support different types of collections. Kotlin builds on and extends this Java Collection API to make working with collections easier and safer.
The main collection types in Kotlin include List, Set and Map.
List
List: A list is an ordered collection of elements. It can contain duplicate elements and their order is preserved. In Kotlin a list is represented by the interface List represented. A list can be created using the function listOf() to be created. For example:
Use cases: Lists are used when the order of elements is important and duplicates are allowed. For example, storing items in the order in which they occur (e.g. a list of users who sign up for a newsletter).
Set
Set: A set is a collection of unique items. It contains no duplicates and the order of elements is not guaranteed. In Kotlin a set is defined by the interface Set represented. A set can with the function setOf() to be created. For example:
Use cases: Sets are used when duplicates should not be allowed and the arrangement of the elements is not important. For example, a collection of unique elements, such as a list of usernames or email addresses, may be used. Sets are useful for quick membership checks, such as determining whether an item is included within a group.
Map
Map: A map is a collection of key-value pairs. Each key is unique and associated with a value. In Kotlin a map is defined by the interface Map represented. A map can be created using the function mapOf() to be created. For example:
Use cases: Maps are used when elements are arranged in the form of key-value pairs and each key is unique. An example of this is storing user information, where the username or email address acts as a key and the associated user data is stored as values. Maps are efficient for quick searches, such as finding a value using a unique key.
Immutable (read-only) and mutable collections
Kotlin distinguishes between immutable (immutable or read-only called) and variable (changeable) Collections. Immutable collections cannot be modified once they are created, while mutable collections provide methods for adding, removing, and modifying items. To put it figuratively, you can think of it like this: Immutable collections are like printed books - they cannot be changed after they have been created. Mutable collections, on the other hand, are like notebooks in which we can add, change or delete things.
All immutable collections include those mentioned above List, Set and Map.
The mutable collections can be changed after they are created. The interfaces MutableList, MutableSet and MutableMap extend the corresponding basic interfaces and add methods for adding, removing and modifying elements.
MutableList
MutableList is used in Kotlin to represent a dynamic, mutable list of elements where the order of the elements is important. The function is used to create the mutable collection MutableList mutableListOf() used. The example below creates a mutable list and then modifies it using standard functions.
Example of use : Collecting and processing data from various sources that then needs to be further processed or analyzed, e.g. For example, when reading data from a file or database, processing API responses, or manipulating data for statistical analysis.
MutableSet
MutableSet is used in Kotlin to represent a mutable collection of unique items where duplicates are undesirable. To create MutableSet, the mutableSetOf() function is used.
Application example: Managing relationships between objects or elements in an application, such as storing "like" interactions in a social media application, where each user can only click "like" once.
MutableMap
MutableList is used to store key-value pairs where each key is unique and values need to be changed, added or removed.
Application example: MutableMaps are well suited for situations where quick access to values based on unique keys is required. Examples include storing user information, where the username or user ID is the key and the associated user data is the value, or storing configuration settings in an application, where the setting names are the keys and the setting values are the associated values.
In addition to the functions already mentioned, Kotlin collections offer a number of other methods for transformations, filtering, sorting and grouping, such as map, filter, groupBy, sortedBy and many more. These functions make it easier to work with collections and make the code simpler and more expressive. The functions will be examined in detail later.
Collection hierarchy
The Collection hierarchy describes how collection classes and interfaces are organized in a hierarchical arrangement. This arrangement includes various interfaces that provide both general and specific functions for different collection types. In this way, diverse collection types can be used and expanded in a consistent and well-structured manner.
The following table provides an overview of the most important interfaces in the collection hierarchy and their relationships to one another. Each interface represents a specific collection type, and the child interfaces extend the capabilities of their parent interfaces to provide additional functionality or variability.
Interface | Description | Subordinate interfaces | Use Cases |
---|---|---|---|
Collection | This is the main interface for all collection types. It offers basic features like size(), isEmpty(), contains(), etc. All other collection interfaces extend this interface | Cunning, Set | ArrayList, HashSet, LinkedList |
List | An ordered collection type that allows duplicates and allows items to be accessed via an index. List extends the collection interface. | MutableList | ArrayList, LinkedList |
MutableList | Ordered collection that allows duplicates and is mutable | - | ArrayList, LinkedList |
Set | Unordered collection that does not allow duplicates | MutableSet | HashSet, LinkedHashSet |
MutableSet | Unordered collection that does not allow duplicates and is mutable | - | HashSet, LinkedHashSet |
Map | A Collection type that organizes elements into key-value pairs. Map is not a direct sub-interface of Collection, but forms a separate hierarchy, but is closely linked to the Collection hierarchy. | MutableMap | HashMap, LinkedHashMap |
MutableMap | Collection of key-value pairs that is mutable | - | HashMap, LinkedHashMap |
Map.Entry | A key-value pair in a map | - | - |
Differences and similarities between arrays and collections
Arrays and Collections have several differences and similarities in functionality, usage and performance. Below are some of the key differences between arrays and the List, Set and Map collection types in Kotlin:
Size and changeability:
- Arrays have a fixed size, which is set at creation and does not change. You can change elements within an array, but you can change its size.
- Collections can have different resizing behaviors depending on whether they are read-only or mutable. Mutable Collections (e.g. MutableList, MutableSet, MutableMap) can grow or shrink, while Readonly Collections (List, Set, Map) cannot change size after creation.
Type hierarchy:
- Arrays are not participants in the collection hierarchy and do not implement the List, Set, or Map collection interfaces.
- List, Set and Map are part of the collection hierarchy and implement the collection interfaces in Kotlin.
Storage of items:
- Arrays store elements in a continuous memory area and provide fast direct access to elements via their index.
- Collections may not store items in a continuous storage area, depending on their internal implementation. Access and manipulation performance may vary depending on the collection type.
Uniqueness and order of elements:
- Arrays can contain duplicate elements and the order of the elements is preserved.
- Lists are similar to arrays in the sense that they contain duplicate elements and the order of the elements is preserved.
- Sets do not contain duplicates and the order of elements is not guaranteed (unless it is a LinkedHashSet, which preserves insertion order).
- Maps store key-value pairs, where each key is unique and associated with a value. The order of the keys is not guaranteed (unless it is a LinkedHashMap that preserves the insertion order).
Generics and type safety:
- Arrays have stronger type safety because they require a specific element type when created.
- Collections also provide type safety through generics, but they can be slightly weaker than arrays due to type erasure at runtime.
Functions and methods:
- Arrays and Collections provide some common functions and methods, such as forEach(), filter(), map(), etc. However, Collections provide additional functions and methods that make working with them easier and more expressive.
Overall, arrays and collections offer different ways to manage groups of elements in Kotlin. Arrays are suitable for scenarios where fixed size and high performance are required. Collections, on the other hand, offer more flexibility and functions that make working with groups of elements easier.