Set operations
- Kotlin course
- Beginner
- Lesson 66/116
- 5 min
Learn set management with add, remove and contains.
Set operations: add, remove, contains
On a mutable set add(x) inserts a new element. If the element already exists it returns false, otherwise true. remove(x) takes the element out and returns true if it was present, false otherwise. contains(x) answers the presence question with a Boolean.
val tags = mutableSetOf("new", "important")
tags.add("urgent") // true
tags.add("new") // false (already there)
tags.remove("important") // trueThese Boolean returns are handy when you want to check whether an element was actually added.
Set operations: union, intersect, subtract
Kotlin sets support union, intersect and subtract. These return a new set; the originals are unchanged.
val a = setOf(1, 2, 3)
val b = setOf(2, 3, 4)
a union b // {1, 2, 3, 4}
a intersect b // {2, 3}
a subtract b // {1}These operations are handy when comparing tag, category or permission sets: which tags are shared, which are only on one side?
Practice Add, remove and print size on a set
Start with mutableSetOf("a", "b"). Add "c" with add, remove "a" with remove and print the size with println(colors.size).
Starter code
fun main() {
val colors = mutableSetOf("a", "b")
// Add "c", remove "a" and print size
}Sample solution
fun main() {
val colors = mutableSetOf("a", "b")
colors.add("c")
colors.remove("a")
println(colors.size)
}Expected output
2
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match method to return value
| Term | Meaning |
|---|---|
add(x) |
true: added / false: already there |
remove(x) |
true: was there / false: absent |
contains(x) |
present? Boolean |
size |
Unique element count |
2 What does set.add("already there") return on a set?
- true (always)
- false (already there) Correct answer
- Unit
- Throws an exception
Explanation: add returns false when the element is already present; true when newly added.
3 Fill in the blank: add to the set
colors.____("yellow")
colors.add("yellow")
Explanation: colors.add("yellow") appends the new color to the set.