Sobes.tech
Junior

Can you tell me about the differences between List, Set, and Map, and when to use each?

sobes.tech AI

Answer from AI

List - an ordered collection that allows duplicates. Elements are accessible by index.

Set - an unordered collection of unique elements. Does not allow duplicates.

Map - a collection of key-value pairs, where each key is unique. Elements are accessible by key.

Comparison table:

Feature List Set Map
Order Yes No In insertion order (not always)
Duplicates Allowed Not allowed Keys are unique, values can duplicate
Access By index By iteration By key
  • Usage:
    • List: When the order of elements matters, and duplicates are allowed (e.g., shopping list, transaction history).
    • Set: When a collection of unique elements is needed, and order does not matter (e.g., set of unique users, list of unique tags).
    • Map: When data needs to be stored as key-value pairs and values should be quickly retrievable by key (e.g., dictionary, app settings).

Example:

// List
val shoppingList = listOf("apple", "banana", "apple")
println(shoppingList[0]) // apple

// Set
val uniqueFruits = setOf("apple", "banana", "apple")
println(uniqueFruits.size) // 2 (apple appears only once)

// Map
val userAges = mapOf("Alice" to 30, "Bob" to 25)
println(userAges["Alice"]) // 30