How to Find Difference of Sets in Kotlin Easily
In Kotlin, you can find the difference of two sets using the
subtract() function or the - operator. Both return a new set containing elements from the first set that are not in the second set.Syntax
To find the difference between two sets in Kotlin, use either:
set1.subtract(set2)- returns a new set with elements inset1not inset2.set1 - set2- a shorthand operator for the same operation.
kotlin
val difference = set1.subtract(set2)
// or
val difference = set1 - set2Example
This example shows how to find the difference between two sets of numbers. It prints the elements that are in the first set but not in the second.
kotlin
fun main() {
val set1 = setOf(1, 2, 3, 4, 5)
val set2 = setOf(3, 4, 6)
val difference1 = set1.subtract(set2)
val difference2 = set1 - set2
println("Difference using subtract(): $difference1")
println("Difference using - operator: $difference2")
}Output
Difference using subtract(): [1, 2, 5]
Difference using - operator: [1, 2, 5]
Common Pitfalls
One common mistake is expecting subtract() or - to modify the original set. These functions return a new set and do not change the original sets.
Also, sets do not allow duplicate elements, so the difference will never contain duplicates.
kotlin
fun main() {
val set1 = mutableSetOf(1, 2, 3)
val set2 = setOf(2)
// Wrong: expecting set1 to change
set1.subtract(set2)
println("After subtract(): $set1") // set1 is unchanged
// Correct: assign the result
val newSet = set1.subtract(set2)
println("New set after subtract(): $newSet")
}Output
After subtract(): [1, 2, 3]
New set after subtract(): [1, 3]
Quick Reference
| Operation | Description | Example |
|---|---|---|
| subtract() | Returns a new set with elements in first set not in second | set1.subtract(set2) |
| - operator | Shorthand for subtract() | set1 - set2 |
| Original sets | Not modified by subtract or - | set1 and set2 remain unchanged |
Key Takeaways
Use
subtract() or - operator to find set difference in Kotlin.These operations return a new set and do not change the original sets.
Set difference contains only elements unique to the first set.
Sets automatically handle duplicates, so no duplicates appear in the result.