Skip to main content

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]
}
Open in Kotlin Playground

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]
}
Open in Kotlin Playground

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
}
Open in Kotlin Playground

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.

Architect trap

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​

  1. What is the difference between A subtract B and B subtract A?
  2. Why can mutating a data-class property break HashSet lookup?
  3. Does the Set interface guarantee iteration order?
  4. How can Set algebra help calculate synchronization work?