Kotlin Set and MutableSet (with Examples)

Kotlin course · Collections · Lesson 29 of 51

A set is a collection of unique items: each value can appear only once. Use a set when you care about whether something is there, not about duplicates or positions.

Creating sets

fun main() {
    val tags = setOf("kotlin", "android", "kotlin", "compose")
    println(tags)          // the duplicate is gone
    println(tags.size)

    val visited = mutableSetOf<String>()
    println(visited.isEmpty())
}

Output:

[kotlin, android, compose]
3
true

Removing duplicates from a list

fun main() {
    val emails = listOf("a@x.com", "b@x.com", "a@x.com", "c@x.com", "b@x.com")
    println(emails.toSet())
    println(emails.distinct())   // same result, but stays a List
}

Output:

[a@x.com, b@x.com, c@x.com]
[a@x.com, b@x.com, c@x.com]

Adding and removing (MutableSet)

fun main() {
    val online = mutableSetOf("Asha", "Ravi")
    println(online.add("Meera"))   // true: added
    println(online.add("Asha"))    // false: already there
    online.remove("Ravi")
    println(online)
}

Output:

true
false
[Asha, Meera]

add() returns true if the value was new. That makes sets handy for “have I seen this before?” checks.

Checking membership

fun main() {
    val admins = setOf("asha", "kabir")
    val user = "kabir"
    if (user in admins) println("$user is an admin")
    println(admins.contains("ravi"))
}

Output:

kabir is an admin
false

Checking in is fast for sets, even with thousands of items, because sets are built for lookups.

Set operations: union, intersect, subtract

fun main() {
    val frontend = setOf("Asha", "Ravi", "Meera")
    val backend = setOf("Ravi", "Kabir", "Meera")

    println(frontend union backend)      // in either team
    println(frontend intersect backend)  // in both teams
    println(frontend subtract backend)   // only in frontend
}

Output:

[Asha, Ravi, Meera, Kabir]
[Ravi, Meera]
[Asha]

Order: LinkedHashSet, HashSet and sortedSetOf

FunctionOrder of items
setOf, mutableSetOfthe order you added them (LinkedHashSet)
hashSetOfno guaranteed order (HashSet, slightly faster)
sortedSetOfsorted (TreeSet)
fun main() {
    println(mutableSetOf(5, 1, 3))
    println(sortedSetOf(5, 1, 3))
}

Output:

[5, 1, 3]
[1, 3, 5]

Sets of your own objects

Sets use equals() and hashCode() to decide what counts as a duplicate. Data classes generate these for you:

data class Point(val x: Int, val y: Int)

fun main() {
    val points = setOf(Point(1, 2), Point(1, 2), Point(3, 4))
    println(points.size)
}

Output:

2

With a regular (non-data) class, two objects with the same values would both be kept, because they’re different objects.

Common mistakes

  • Expecting an index: sets have no set[0]. Use first() or convert to a list.
  • Using a set when duplicates matter: a shopping cart with two of the same item needs a list or a map of counts.
  • Changing an object inside a set: if a field used by hashCode() changes, the set can no longer find it. Keep set items immutable.

Exercise

Find the words that appear in both sentences, and the unique words across both.

fun main() {
    val a = "kotlin is fun and kotlin is fast".split(" ").toSet()
    val b = "java is old but java is stable".split(" ").toSet()

    println("Common: ${a intersect b}")
    println("All unique: ${(a union b).sorted()}")
}

Output:

Common: [is]
All unique: [and, but, fast, fun, is, java, kotlin, old, stable]

FAQ

What is a Set in Kotlin?

A collection that holds each value only once. setOf(1, 1, 2) contains just 1 and 2.

How do I remove duplicates from a list in Kotlin?

list.distinct() keeps a list. list.toSet() gives a set.

Does a Kotlin set keep insertion order?

setOf and mutableSetOf do (they’re LinkedHashSet). hashSetOf doesn’t guarantee any order.

WhatsApp us📞 Call now