Set vs List in Kotlin: Key Differences and Usage Guide
List is an ordered collection that allows duplicate elements, while a Set is an unordered collection that stores unique elements only. Use List when order matters and duplicates are allowed, and Set when you need to ensure no duplicates and order is not important.Quick Comparison
Here is a quick side-by-side comparison of Set and List in Kotlin based on key factors.
| Factor | List | Set |
|---|---|---|
| Order | Maintains insertion order | No guaranteed order |
| Duplicates | Allows duplicates | No duplicates allowed |
| Access by index | Yes, supports indexing | No indexing support |
| Common use case | When order and duplicates matter | When uniqueness matters |
| Implementation examples | ArrayList, LinkedList | HashSet, LinkedHashSet, TreeSet |
Key Differences
List in Kotlin is an ordered collection. This means the elements keep the order you add them in, and you can access elements by their position using an index. Lists allow duplicate elements, so the same value can appear multiple times.
On the other hand, Set is a collection that stores unique elements only. It does not allow duplicates, so if you try to add an element that already exists, it will be ignored. Sets do not guarantee the order of elements, except for some implementations like LinkedHashSet which preserve insertion order.
Because of these differences, List is best when you care about the order and want to keep duplicates, such as a list of tasks or names. Set is ideal when you want to ensure no duplicates, like a collection of unique IDs or tags.
Code Comparison
Here is how you create and use a List in Kotlin to store some names, including duplicates, and access elements by index.
fun main() {
val names: List<String> = listOf("Alice", "Bob", "Alice", "Charlie")
println("List contents: $names")
println("First element: ${names[0]}")
println("Contains 'Bob'? ${names.contains("Bob")}")
}Set Equivalent
Here is the equivalent code using a Set to store unique names. Notice duplicates are removed automatically and there is no index access.
fun main() {
val uniqueNames: Set<String> = setOf("Alice", "Bob", "Alice", "Charlie")
println("Set contents: $uniqueNames")
println("Contains 'Bob'? ${uniqueNames.contains("Bob")}")
}When to Use Which
Choose List when you need to keep the order of elements and allow duplicates, such as storing user inputs, logs, or ordered tasks. Use Set when you want to ensure all elements are unique and order does not matter, like storing unique IDs, tags, or categories.
If you want uniqueness but also care about order, consider using LinkedHashSet which combines both features.
Key Takeaways
List for ordered collections that allow duplicates and support indexing.Set for collections that require unique elements without duplicates.List maintains insertion order; Set does not guarantee order unless using LinkedHashSet.List, not with Set.