๐ŸŽ“ A1Learner
๐Ÿ”

Kotlin Sets

A set is a collection that holds each value once. Writing the same value twice still leaves one copy in the set.

A repeat kept once

The word red is written twice in the code. The printed set shows red only once.

fun main() {
    val colors = setOf("red", "blue", "red")
    println(colors)
}

Asking if a value is in the set

The contains calls ask about blue and green. The answers print as true and false.

fun main() {
    val colors = setOf("red", "blue", "red")
    println(colors.contains("blue"))
    println(colors.contains("green"))
}

The count after repeats are dropped

Three words are written, and one is a repeat. The size prints 2, not 3.

fun main() {
    val colors = setOf("red", "blue", "red")
    println(colors.size)
}

Example

fun main() {
    val colors = setOf("red", "blue", "red", "green")
    println(colors)
    println(colors.size)
    println(colors.contains("red"))
}

Key points

  • setOf: the call that builds a set from values.
  • A repeated value is kept only once.
  • Use .contains to ask if a value is in the set.
  • size: the .size value counts the values left after repeats are dropped.

In this example, the set is written with red twice. The print shows red once, in the first place it was written. The size prints 3, and contains for red prints true.

Note

A set prints its values in the order they were written.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Kotlin Playground

Exercise

How many values does setOf("red", "blue", "red") hold?