In Kotlin, list, set, and map are three commonly used collection types.
A list is an ordered collection of elements where each element can be accessed by its index. This means that elements in a list can be accessed in the order in which they are stored. Lists can contain duplicate elements, and elements can be added, removed, or modified.
Example usage of list in Kotlin:
val numbers = mutableListOf(1, 2, 3, 4, 5)
numbers.add(6)
println(numbers) // Output: [1, 2, 3, 4, 5, 6]
A set is an unordered collection of unique elements. Sets cannot contain duplicates, and elements can be added or removed. Unlike lists, sets do not allow random access, so we cannot access an element in a set by its index.
Example usage of set in Kotlin:
val uniqueNumbers = mutableSetOf(1, 2, 3, 4, 5, 5)
println(uniqueNumbers) // Output: [1, 2, 3, 4, 5]
uniqueNumbers.add(6)
println(uniqueNumbers) // Output: [1, 2, 3, 4, 5, 6]
A map is a collection of key-value pairs. Each key in a map must be unique, and each key is associated with a value. Like sets, maps are unordered collections, so we cannot access a value in a map by its index, but we can access the value by its key.
Example usage of map in Kotlin:
val userAges = mutableMapOf(
"Alice" to 25,
"Bob" to 30,
"Charlie" to 35
)
userAges["Alice"] = 26
userAges["David"] = 40
println(userAges) // Output: {Alice=26, Bob=30, Charlie=35, David=40}
When to use each collection type:
- Use a list when you need to store elements in a specific order and duplicates are allowed. Lists are useful when you need to access elements by their index.
- Use a set when you need to store unique elements and order doesn’t matter. Sets are useful when you need to check if an element is already in the collection.
- Use a map when you need to associate a value with a key. Maps are useful when you need to retrieve a value based on a specific key.