Beginner 6 min readKotlin 2.0

Kotlin Set — setOf and mutableSetOf

A Set is a collection that contains no duplicate elements. Kotlin has read-only (setOf) and mutable (mutableSetOf) sets.

What You Will Learn

  • Create sets with setOf and mutableSetOf
  • Understand set uniqueness
  • Check membership
  • Perform set operations: union, intersect, subtract

Creating Sets

Sets automatically remove duplicates. Order is not guaranteed for HashSet.

setOf

kotlin
fun main() {
    val set1 = setOf(1, 2, 3, 2, 1)
    println(set1)
    println(set1.size)
    println(set1.contains(2))
    println(4 in set1)
}
Output
[1, 2, 3] 3 true false

Duplicate values 2 and 1 are removed. The resulting set has 3 unique elements.

Beginner Tip: Use a Set when you only care if an element is present, not how many times. Sets are faster for membership checks than lists on large data.

Mutable Set

mutableSetOf allows adding and removing elements.

mutableSetOf

kotlin
fun main() {
    val colors = mutableSetOf("Red", "Green", "Blue")
    colors.add("Yellow")
    colors.add("Red")  // duplicate — ignored
    colors.remove("Green")
    println(colors)
}
Output
[Red, Blue, Yellow]

Adding "Red" again has no effect — the set already contains it. .remove() removes the specified element.

Set Operations

Kotlin supports mathematical set operations: union, intersection, and subtract.

Set Operations

kotlin
fun main() {
    val a = setOf(1, 2, 3, 4)
    val b = setOf(3, 4, 5, 6)
    println(a union b)        // all elements from both
    println(a intersect b)    // elements in both
    println(a subtract b)     // in a but not in b
}
Output
[1, 2, 3, 4, 5, 6] [3, 4] [1, 2]

union combines both sets. intersect returns common elements. subtract removes b's elements from a.

Practice Exercise

Exercisepredict output

What prints? val s = setOf(1,2,3,2,1) println(s.size)

Quick Quiz

Quick Quiz

What happens when you add a duplicate to a Set?

Frequently Asked Questions

Related Tutorials

Last updated: 2026-05-01Kotlin 2.0

Written by KotlinGuide Editorial Team · Reviewed by KotlinGuide Technical Review