Kotlin Collections
--
Objects in a collection are called elements or items.
The working structure of collections is the same in Kotlin as in another programming language like JAVA.
Collection types
Some of the collections are mostly used in Kotlin.
The Kotlin Standard Library provides implementations for basic collection types: sets, lists, and maps.
A pair of interfaces represent each collection type:
- A read-only interface that provides operations for accessing collection elements.
- A mutable interface that extends the corresponding read-only interface with the write operations: adding, removing, and updating its elements.
List — A list is a collection of integer types of Data that reflects their position. A duplicate element can be stored in the list.
Set — it's a collection of unique elements. They are unique, but The order of elements is not important.
Map — is a set of key-value pairs. Keys are unique, and each of them maps to exactly one value. Values can be duplicated. Maps are useful for storing logical connections between objects.
Kotlin's collection interface diagram
List :
List<T> stores elements in a specified order. List elements (including null) can duplicate.
val numbers = listOf("one", "two", "three", "four")
println("Number of elements: ${numbers.size}")
//output: Number of elements: 4
MutableList<T> is a List with list-specific write operations, for example, to add or remove an element at a specific position.
val numbers = mutableListOf(1, 2, 3, 4)
numbers.add(5)
numbers.removeAt(1)
numbers[0] = 0
numbers.shuffle()
println(numbers)
//output :[5, 3, 4, 0]
in Kotlin, The default implementation of MutableList is ArrayList.
Set :
Set<T> stores unique elements, NULL elements are also unique.
Two SET can be equal if they have the same size and for each element of a set, there is an equal element in the other set.
val numbers = setOf(1, 2, 3, 4)
println("Number of elements: ${numbers.size}")
if (numbers.contains(1)) println("1 is in the set")
val numbersBackwards = setOf(4, 3, 2, 1)
println("The sets are equal: ${numbers == numbersBackwards}")
//Number of elements: 4
//1 is in the set
//The sets are equal: true
Map :
A map is a collection that contains pairs of objects.
The map holds the data in the form of pairs, which consists of a key and a value.
Map keys are unique, and the map holds only one value for each key.
There are two kinds of Map:
- Immutable Maps: For the variable whose value can’t change, here we should use mapOf() operator. It means we can define once, but we can't change.
- Mutable Maps: when we need to do read and write operations, here we can use mutableMapOf().
fun <K, V> mapOf(vararg pairs: Pair<K, V>): Map<K, V>
- The first value of the pair is the key, and the second is the value of the corresponding key.
- If multiple pairs have the same key, then the map will return the last pair value.