CodeGym /Courses /Kotlin SELF /Set and MutableSet — uniqueness and membership checks

Set and MutableSet — uniqueness and membership checks

Kotlin SELF
Level 19, Lesson 2
Available

1. Why do you need a Set if you already have a List?

If a List is like “a line of people holding numbered tickets,” a Set is like “a guest list at the entrance,” where only one thing matters: a person is either on the list or they aren’t. In programming, this model shows up all the time: “allowed commands,” “unique tags,” “already processed values,” “don’t add again.” Set helps you express this idea directly, rather than via hacks like “I’ll check the list before adding.”

From Kotlin’s point of view, Set<T> stores unique elements: the same value cannot exist inside the set “in two copies.” People also usually say that order in a set is not part of the meaning. The documentation puts it like this: Set stores unique elements, and their order is “usually undefined.”

Imagine you’re building a small console app that stores expense records (we started this in the previous lecture using lists). At some point you will almost certainly want to:

  • store the list of expenses (duplicates are allowed there: you can buy coffee 200 times);
  • but also keep a unique set of categories that have already appeared (to show hints or validate input).

That is a classic use case for Set.

2. Set and MutableSet: reading and changes

When you first see Set and MutableSet, it’s very tempting to think: “Ah, Set is like val, and MutableSet is like var.” And this is where Kotlin smiles slyly.

Set<T> is a read-only interface: size, presence checks, iteration.
MutableSet<T> is a mutable interface: adding, removing.

So the difference is not whether you can change the variable, but rather which operations are available through the type. This style is the same as with List/MutableList.

One more important point: a mutable set should almost always be stored in a val. Then you won’t accidentally “rebind” the variable to a different set, but you can still honestly change the contents via add/remove. This idea already appeared in the Kotlin collections overview: val protects the reference, but does not forbid write operations on a mutable collection.

Creating sets: setOf, mutableSetOf, empty sets

When you’re just starting out, the most convenient way to create sets is via factory functions from the standard library. They read like “create a list/set for me right now,” without extra noise. And it also fits perfectly with the familiar style of listOf(...) and mutableListOf(...), which we already used for lists.

setOf(...) and “collapsing” duplicates

fun main() {
    val tags = setOf("kotlin", "kotlin", "jvm")

    println(tags)        // [kotlin, jvm]
    println(tags.size)   // 2
}

What matters here is not the order the set is printed in, but the fact that the duplicate "kotlin" does not create a second element. Set is about uniqueness, not about “how many times it occurred.”

Empty set: sometimes you need an explicit type

Just like with lists, an empty collection often requires a hint to the compiler: “what element type do you expect here?”

fun main() {
    val usedCategories = mutableSetOf<String>()

    usedCategories.add("food")
    println(usedCategories) // [food]
}

If you try to write just mutableSetOf() without <String>, Kotlin can honestly respond: “I don’t know what should go in here.” And it will be right.

3. Basic set operations

Uniqueness as a contract: add() and the returned Boolean

In a list, add() almost always means “the element definitely got added (to the end).” In a set it’s more interesting: add(x) means “try to add it, but if such an element already exists — change nothing.” That’s why the operation returns a Boolean: whether a new element was actually added.

This is very useful when you want to “notify once” or “avoid duplicating an action.”

fun main() {
    val seen = mutableSetOf<Int>()

    println(seen.add(10)) // true
    println(seen.add(10)) // false
    println(seen)         // [10]
}

The second attempt did not add “another ten” — it simply isn’t needed in terms of the set’s meaning.

Membership check: contains() and the in operator

The most “natural” operation for a Set is the question: “Is this element in here?” In Kotlin you can do it in two equally correct ways: via contains(x) and via x in set. The second option usually reads nicer, especially in conditions.

And yes, that is one of the reasons why sets are loved for “allowed/forbidden” checks: the code becomes almost conversational.

fun main() {
    val allowedCommands = setOf("add", "list", "remove")

    val cmd = "list"
    println(cmd in allowedCommands) // true
}

At this point it’s very handy to keep this mental model: Set is “a set of allowed values.” It’s not about order, not about indices, and definitely not about “delete element number 3.”

Removal: remove() and what it returns

Removal in a MutableSet is similar to remove(value) on a list, but it’s more natural semantically: sets have no indices, so removal is always “by value.” Just like add, it returns a Boolean: whether something was actually removed.

fun main() {
    val usedCategories = mutableSetOf("food", "transport")

    println(usedCategories.remove("food")) // true
    println(usedCategories.remove("food")) // false
    println(usedCategories)                // [transport]
}

The second time there is nothing to remove — "food" is already absent.

4. Order, equality, and “remove duplicates”

Can you rely on order in a Set?

Intuitively you want to think: “Well, it prints like "[a, b, c]", so there is an order.” And Kotlin indeed often behaves so that the order looks stable. But it’s important to separate “how it happens to be implemented today” from “what the data structure means.”

Formally, Set is a set: unique elements, and order “is not the main thing at all.”
At the same time, in the Kotlin standard library the default implementation of MutableSet is LinkedHashSet, and it preserves insertion order, so first() and last() can be predictable specifically with this implementation.

A practical beginner rule sounds like this: treat Set as a container where order is not part of the contract. If your logic falls apart when elements are permuted, you most likely need a different structure (usually a list).

“Remove duplicates”: toSet() as a quick uniqueness filter

One of the most common practical scenarios: you already have a list (or an array) with duplicates, but you need a set of unique values. For example, the user entered categories in an arbitrary way, and you want to get a “list of all unique categories.”

That’s what toSet() is for. It creates a new collection and “collapses” duplicates. It’s important that copy/convert functions like toSet() take a snapshot at the moment of the call: changes to the source collection later do not “magically” reflect in the result.

fun main() {
    val words = listOf("a", "b", "a", "c")
    val uniqueWords = words.toSet()

    println(uniqueWords)      // [a, b, c]
    println(uniqueWords.size) // 3
}

The same works for arrays: you can turn an array into a Set and see that duplicates disappear, whereas if you convert it to a List — they remain.

Set equality: elements matter more than order

For lists, equality depends on order: [1, 2] is not equal to [2, 1]. For sets, the logic is different: if the elements are the same, the sets are equal, even if you created them “in different orders.” This matches the mathematical meaning of a set and is useful in real life when you compare sets of permissions/tags/features.

In Kotlin documentation, this is shown with an example: sets are equal if they contain the same elements.

fun main() {
    val a = setOf(1, 2, 3, 4)
    val b = setOf(4, 3, 2, 1)

    println(a == b) // true
}

5. Example: expense tracking and unique categories

Now we’ll continue our mini-project of the day: “console expense tracking,” without classes and without complex architecture — just to get hands-on practice with collections. In the previous lecture we stored expense records in MutableList<Triple<String, String, Int>>, where the fields are category, description, and amount.

Now we’ll add one more structure: MutableSet<String> for unique categories that have already appeared. This gives us two useful things: a quick answer to “has this category already existed?” and the ability at any moment to get a “list of categories without duplicates,” without manually iterating through the whole list.

Mini data diagram

Let’s draw a very simple diagram so your head doesn’t try to keep everything in memory (memory is expensive, especially on Monday morning):

flowchart LR
    Records["records: MutableList⟨Triple⟨Category, Title, Amount⟩⟩"]
    Categories["knownCategories: MutableSet⟨Category⟩"]

    Records -->|"dobavili zapis'"| Categories

Idea: each new record can “contribute” a new category to the set. If the category already existed — the set simply won’t change.

Code: adding a record and updating the set of categories

Here we deliberately write small functions and short examples so the code reads like a textbook rather than “adult production” (it will catch up to you later).

fun addExpense(
    records: MutableList<Triple<String, String, Int>>,
    knownCategories: MutableSet<String>,
    category: String,
    title: String,
    amount: Int
) {
    records.add(Triple(category, title, amount))
    knownCategories.add(category)
}

Notice: knownCategories.add(category) doesn’t break anything, even if the category already existed. That’s the beauty of a set: it protects us from duplicates by contract.

Checking “new category or not” via add()

Now we’ll use the fact that add returns a Boolean to print a useful message to the user (or to ourselves during debugging): whether the category is new or not.

fun addCategoryIfNew(knownCategories: MutableSet<String>, category: String) {
    val added = knownCategories.add(category)

    if (added) {
        println("New category: $category") // for example: New category: food
    } else {
        println("Category already existed: $category") // for example: Category already existed: food
    }
}

A list can’t do this “out of the box”: with a list you would have to do contains separately, and then add, and it’s easy to make a mistake (or simply forget).

Full mini example: records and categories

Let’s assemble a small main that demonstrates the idea end-to-end. It doesn’t aim to be a full-fledged interface — it’s an educational “sandbox” where we manually check that data structures behave as promised.

fun main() {
    val records = mutableListOf<Triple<String, String, Int>>()
    val knownCategories = mutableSetOf<String>()

    addExpense(records, knownCategories, "food", "coffee", 300)
    addExpense(records, knownCategories, "transport", "taxi", 1200)
    addExpense(records, knownCategories, "food", "lunch", 550)

    println(records.size)              // 3
    println(knownCategories)           // [food, transport] (poryadok ne schitaem kontraktom)
    println("food" in knownCategories) // true
}

You can clearly see it here: there are three records (two of them in the "food" category), but only two categories — because a set stores unique values.

6. Set and null: yes, you can — but be careful

Sometimes data arrives “dirty”: the category failed to parse, the user entered an empty string, and you haven’t cleaned it up yet. Since we’ve already covered null-safety, it’s useful to know: Set can store null, but as a unique element — at most one null in the set. The documentation explicitly says that null in a Set is unique as well: a second null will not appear.

This is not a call to store null everywhere you can (we’re not collecting problems), but it’s useful knowledge for debugging and transitional states.

fun main() {
    val categories: MutableSet<String?> = mutableSetOf()

    categories.add(null)
    categories.add(null)

    println(categories.size) // 1
    println(categories)      // [null]
}

7. Typical mistakes when working with Set and MutableSet

Mistake #1: expecting the set to store duplicates “like a list.”
Beginners often add the same value to a MutableSet and are surprised: “Why isn’t the size growing?” Because Set is meant to store unique elements. If you need to store “every user input,” even if it repeats, that’s a list task. And if you need to store “which values have appeared at all,” that’s a set task.

Mistake #2: writing logic that depends on element order in a Set.
Sometimes everything looks as if there is an order, and your hand reaches to do “I’ll take the first element and consider it the main one.” Kotlin often uses an implementation that preserves insertion order, but the meaning of Set is not that. As soon as you start relying on order, the code becomes fragile: the implementation changes, the data source changes, and the behavior unexpectedly drifts.

Mistake #3: trying to index into a Set.
After List you really want to write something like mySet[0]. But a set has no indices as part of its model. That’s a signal you picked the wrong container for the task. If you need position — take a List. If you need uniqueness and “present/absent” checks — take a Set.

Mistake #4: forgetting that add/remove return Boolean, and losing useful information.
Many people just call add(x) and ignore the result, even though it’s an almost free hint about whether a change actually happened. When you validate input or keep a set of “already seen values,” this Boolean helps you write simpler, clearer code: “if it was added for the first time — notify/do an action, otherwise — skip.”

Mistake #5: creating an empty mutableSetOf() without a type and getting a compilation error.
An empty collection gives the compiler no hints, so sometimes you need to specify the type explicitly: mutableSetOf<String>(). That’s normal and does not make you a “worse programmer.” If anything, it’s the opposite: you explicitly pin down the contract, and Kotlin stops guessing what you meant.

1
Task
Kotlin SELF, level 19, lesson 2
Locked
Command validation
Command validation
1
Task
Kotlin SELF, level 19, lesson 2
Locked
Words without duplicates
Words without duplicates
1
Task
Kotlin SELF, level 19, lesson 2
Locked
Guest Registration
Guest Registration
1
Task
Kotlin SELF, level 19, lesson 2
Locked
Subscription Console
Subscription Console
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION