Creating sets
- Kotlin course
- Beginner
- Lesson 65/116
- 5 min
Learn to create sets with setOf and mutableSetOf.
Creating sets: setOf and mutableSetOf
A set holds unique elements: if you add the same element twice, only one copy is kept. setOf returns a read-only set, while mutableSetOf gives a mutable set.
val fruits = setOf("apple", "banana", "apple")
println(fruits) // [apple, banana]The second "apple" is dropped; the set keeps a single apple. Unlike a list, a set has no index concept; elements are unique by content, not by position.
Automatic deduplication
A set stores elements by content, not by insertion order. If an element is already present, a second add is silently dropped. This is handy for deduplicating data in one shot.
val tags = mutableSetOf("new", "important", "new")
println(tags.size) // 2
println(tags.contains("new")) // truesize gives the count of unique elements. contains returns a Boolean telling whether the element is in the set; same as with a list.
Practice Print a set with a duplicate
Create a setOf("apple", "banana", "apple") (third element repeats) and print it with println. You will see the duplicate dropped.
Starter code
fun main() {
// Give three fruit names (repeat one) and print the set
}Sample solution
fun main() {
val fruits = setOf("apple", "banana", "apple")
println(fruits)
}Expected output
[apple, banana]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which one creates a mutable set?
- mutableSetOf(1, 2, 3) Correct answer
- setOf(1, 2, 3)
- mutableListOf(1, 2, 3)
- list(1, 2, 3)
Explanation: mutableSetOf gives a mutable set; add and remove work.
2 Fill in the blank: read-only set
val colors = ____("red", "green", "blue")
val colors = setOf("red", "green", "blue")
Explanation: setOf("...") builds a read-only set.
3 Match set expression to behavior
| Term | Meaning |
|---|---|
setOf(...) |
Read-only set |
mutableSetOf(...) |
Mutable set |
size |
Unique element count |
contains(x) |
Is x present? Boolean |