# Sets

A Set is a collection that allows only one element of each value.

The most common Set activity is to test for membership using in or contains():

// Sets/Sets.kt
import atomictest.eq

fun main() {
  val intSet = setOf(1, 1, 2, 3, 9, 9, 4)
  // No duplicates:
  intSet eq setOf(1, 2, 3, 4, 9)

  // Element order is unimportant:
  setOf(1, 2) eq setOf(2, 1)

  // Set membership:
  (9 in intSet) eq true
  (99 in intSet) eq false

  intSet.contains(9) eq true
  intSet.contains(99) eq false

  // Does this set contain another set?
  intSet.containsAll(setOf(1, 9, 2)) eq true

  // Set union:
  intSet.union(setOf(3, 4, 5, 6)) eq
    setOf(1, 2, 3, 4, 5, 6, 9)

  // Set intersection:
  intSet intersect setOf(0, 1, 2, 7, 8) eq
    setOf(1, 2)

  // Set difference:
  intSet subtract setOf(0, 1, 9, 10) eq
    setOf(2, 3, 4)
  intSet - setOf(0, 1, 9, 10) eq
    setOf(2, 3, 4)
}

This example shows:

  1. Placing duplicate items into a Set automatically removes those duplicates.
  2. Element order is not important for sets. Two sets are equal if they contain the same elements.
  3. Both in and contains() test for membership.
  4. You can perform the usual Venn-diagram operations like checking for subset, union, intersection and difference, using either dot notation (set.union(other)) or infix notation (set intersect other). The functions union, intersect and subtract can be used with infix notation.
  5. Set difference can be expressed with either subtract() or the minus operator.

To remove duplicates from a List, convert it to a Set:

// Sets/RemoveDuplicates.kt
import atomictest.eq

fun main() {
  val list = listOf(3, 3, 2, 1, 2)
  list.toSet() eq setOf(1, 2, 3)
  list.distinct() eq listOf(3, 2, 1)
  "abbcc".toSet() eq setOf('a', 'b', 'c')
}

You can also use distinct(), which returns a List. You may call toSet() on a String to convert it into a set of unique characters.

As with List, Kotlin provides two creation functions for Set. The result of setOf() is read-only. To create a mutable Set, use mutableSetOf():

// Sets/MutableSet.kt
import atomictest.eq

fun main() {
  val mutableSet = mutableSetOf<Int>()
  mutableSet += 42
  mutableSet += 42
  mutableSet eq setOf(42)
  mutableSet -= 42
  mutableSet eq setOf<Int>()
}

The operators += and -= add and remove elements to Sets, just as with Lists.

Exercises and solutions can be found at www.AtomicKotlin.com.