Skip to Content
Course content

83: Set Operations: union, intersect, subtract

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Imagine you're organizing two different dinner parties. For the first party, you've invited your college friends. For the second, you've invited your current coworkers. Now, if you want to figure out how many total unique people you need to buy drinks for, you aren't just adding the two lists together—because some of your coworkers actually went to college with you. You need a list of everyone, but without duplicates. That's a union.

If you want to find out who the "bridge" people are—the ones who belong to both social circles—you're looking for the intersection. And if you want to see which college friends aren't coworkers (maybe to avoid talking shop all night), you're subtracting the coworker list from the college list. In Kotlin, these aren't just conceptual ideas; they are built-in functions for Sets that make this kind of logic trivial.

Combining everything with union

When you use union(), you're essentially saying, "Give me everything from both sets, but if something appears in both, only keep it once." Since a Set by definition cannot contain duplicates, this is the most natural way to merge two collections while keeping them clean.

val developerSkills = setOf("Kotlin", "Java", "SQL")
val managerSkills = setOf("Kotlin", "Jira", "Budgeting")

val totalTeamCapabilities = developerSkills.union(managerSkills)
// Result: [Kotlin, Java, SQL, Jira, Budgeting]

I've found that union() is incredibly useful when you're aggregating data from multiple API calls where the same item might be returned in different endpoints.

Finding the common ground using intersect

The intersect() function is your go-to for finding overlapping elements. It returns a set containing only the elements that exist in both the original set and the collection you pass in. If there's no overlap, you just get an empty set back.

val requiredSkills = setOf("Kotlin", "SQL", "AWS")
val candidateSkills = setOf("Kotlin", "Java", "SQL")

val matchingSkills = requiredSkills.intersect(candidateSkills)
// Result: [Kotlin, SQL]

Notice how "AWS" and "Java" disappeared? They didn't make the cut because they weren't common to both lists. It's a very efficient way to handle filtering logic without writing a bunch of if statements inside a filter block.

Filtering out the overlap with subtract

Finally, we have subtract(). This is essentially "Set A minus Set B." It takes the first set and removes anything that also appears in the second set. The order matters here—subtracting A from B is very different from subtracting B from A.

val currentProjectDependencies = setOf("Ktor", "Serialization", "Coroutines")
val sharedLibraryDependencies = setOf("Serialization", "Coroutines")

val uniqueProjectDeps = currentProjectDependencies.subtract(sharedLibraryDependencies)
// Result: [Ktor]

I use this all the time when I need to find "missing" items. For example, if you have a list of all required configuration keys and a list of keys actually present in a config file, subtracting the present keys from the required ones gives you exactly what's missing from the file.




📋 Practical Task

Building a Role-Based Permission Auditor

You are building a security module for an application. You have two sets of permissions: adminPermissions and editorPermissions. Your task is to create a report that calculates three specific things using set operations.

Requirements:

  • Define a set adminPermissions containing: "CREATE_USER", "DELETE_USER", "EDIT_CONTENT", "PUBLISH_CONTENT", "VIEW_LOGS".
  • Define a set editorPermissions containing: "EDIT_CONTENT", "PUBLISH_CONTENT", "VIEW_DASHBOARD".
  • Create a set called allPossiblePermissions that combines every unique permission from both roles.
  • Create a set called sharedPermissions that identifies which permissions both roles have in common.
  • Create a set called exclusiveAdminPermissions that lists permissions only the admin has (and the editor does not).

Print all three resulting sets to the console to verify your logic.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.