It’s time to continue our learning path in Kotlin. The subject covered in this new post is represented by Collections and data operations applied to them.
Collections are actually a set of classes and interfaces that provides high quality implementations of useful data structures and algorithms that help developers to reduce the programming effort and time.
In Kotlin there are different flavors of collections. Just like Java, all collection interfaces are originated from the Iterable interface. The main difference between Java and Kotlin is that in Kotlin we have mutable and immutable collections. An important thing to mention here is that immutable collections in Kotlin are simply read-only.
So in terms of collections these are the main ones:
- Pair – a tuple of two values and Triple – a tuple of three values.
- Array – indexed fixed-sized collection of objects and primitives.
- List – ordered collection of objects.
- Set – unordered collection of objects.
- Map – associative dictionary or map of keys and values.
1️⃣ Pair and Triple
Very helpful if we want to quickly create two (Pair) or three objects (Triple) as a collection
data class Pair<out A, out B> : Serializable
data class Triple<out A, out B, out C> : Serializable
A memory block that keeps multiple values in a sequence; very helpful for low-level optimizations.
Both the immutableArray and mutableArray arrays are fixed in size, but the elements of each array are mutable and can be updated. The only difference is that immutableArray is declared with the val keyword, so this array cannot be reassigned.
Data structures that hold a number of items in a sequence. Kotlin provides two different types of lists:
- immutable lists (does not have add function)
- mutable lists
interface List<out E> :Collection<E>
interface MutableList<E> : List<E>, MutableCollection<E>
Unordered collections of elements. Other than using setOf() / Set<T> and mutableSetOf() / MutableSet<T> we could also use hashSetOf() / java.util.HashSet<T>
interface Set<out E> : Collection<E>
interface MutableSet<E> : Set<E>, MutableCollection<E>
Keeps a collection of key-value pairs.
interface Map<K, out V>
interface MutableMap<K, V> : Map<K, V>
🕵️♀️Data operations in a collection
📌 Aggregate functions
📌 Search functions
📌 Filter functions
📌 Transform functions
Check here my previous articles about Kotlin:
Enjoy and feel free to leave a comment if something is not clear or if you have questions. And if you like it please share!
Thank you for reading! 🙌🙏😍✌
Follow me on: