Set algebra and membership modeling
Sets model membership where duplicates have no meaning. Their algebra answers practical questions such as “What is shared?”, “What exists in either group?”, and “What must be added or removed?”
union, intersect, and subtract
fun main() {
val current = setOf("camera", "location")
val required = setOf("location", "notifications")
println(current union required)
// [camera, location, notifications]
println(current intersect required)
// [location]
println(required subtract current)
// [notifications]
}
Direction matters for subtraction:
required subtract current = requirements still missing
current subtract required = currently held values no longer required
Synchronization difference calculation
fun main() {
val localIds = setOf(1, 2, 3)
val remoteIds = setOf(2, 3, 4)
val upload = localIds subtract remoteIds
val download = remoteIds subtract localIds
val unchanged = localIds intersect remoteIds
println("upload=$upload") // [1]
println("download=$download") // [4]
println("unchanged=$unchanged") // [2, 3]
}
The set calculation identifies membership differences; it does not resolve changed contents, deletions, timestamps, or conflicts for records sharing an ID.
Equality and hash stability
data class User(var id: Int, val name: String)
fun main() {
val user = User(1, "Rakesh")
val users = hashSetOf(user)
println(users.contains(user)) // true
user.id = 2
println(users.contains(user)) // may be false: hash changed
}
Do not mutate properties participating in equals/hashCode while an element is stored in a hash-based Set. The element can end up in a bucket inconsistent with its new hash.
Order is not the Set contract
Kotlin's common setOf implementation often preserves insertion order, but the Set interface promises uniqueness, not universal stable ordering. Use a suitable ordered implementation or sort into a List when order is a product requirement.
Using a Set to deduplicate server records chooses equality as a data-loss policy. Confirm that equality fields really identify the same domain entity and decide which duplicate payload wins before discarding information.
Interview questions
- What is the difference between
A subtract BandB subtract A? - Why can mutating a data-class property break HashSet lookup?
- Does the Set interface guarantee iteration order?
- How can Set algebra help calculate synchronization work?