Hello friends, In this tutorial we will learn the key differences between List, Map, and Set in Kotlin. We will explain each collection type with code examples so you will understand their differences.
List vs Map vs Set in Kotlin: Differences, Comparison & Code Examples
Let’s explore them one by one then with their key differences.
1. List in Kotlin: In a list the data collection is ordered, and each element can be accessed through its index position. The index position always starts from Zero and the list can contain duplicate elements.
1 2 3 4 5 6 7 |
val mutableFruitList = mutableListOf("Apple", "Banana") mutableFruitList.add("Cherry") println(mutableFruitList) // Output: [Apple, Banana, Cherry] |
2. Map in Kotlin: In a Map, data collection is based on Key-Value pairs. In the map, Each key should be unique, and with the key, we can access the value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
fun main() { val mutableFruits = mutableMapOf("apple" to 1, "banana" to 2, "apple" to 1, "mango" to 1) // "apple" is the KEY and "1" is its value. // "banana" is the KEY and "2" is its value. // "mango" is the KEY and "1" is its value. println(mutableFruits) } // Output {apple=1, banana=2, mango=1} |
3. Set in Kotlin: In a set, the stored data is in an unordered format. The set does not allow duplicate items.
1 2 3 4 5 6 |
val mutableSet = mutableSetOf("Apple", "Banana") mutableSet.add("Cherry") println("Mutable Set: $mutableSet") // Output Mutable Set: [Apple, Banana, Cherry] |
Side-by-side comparison of List, Map, and Set:
Feature | List | Map | Set |
---|---|---|---|
Order | Data is in ordered format | Data is in unordered format. | Data is in an unordered format |
Duplicate elements | Allowed | The values can be duplicated but the Key will be Unique. | Not allowed |
Key-Value pair | No | Yes | No |
Value can be accessed by its index position | Yes | No (Only be accessed by its Key). | No |
Usages in Kotlin | To store a collection of items. Duplicasy allowed. | To store data in pairs. | To store unique items. |
When to use | When we want data in an ordered way, data can also have duplicate items. | Store data in Key-value Pairs and further manage like a class management system. | When you only want the collection of Unique elements, |
Conclusion:
By understanding how List, Map, and Set work in Kotlin, you can make more precise decisions about where to use each in a specific scenario. Each has its unique strength and uniqueness in targeting a specific case, Happy coding.