Various Ways to Use Kotlin Set

Introduces various ways to use Set, including setOf, mutableSetOf, union, intersection, and minus.

Set Overview

Kotlin’s Set is a collection based on Java’s Set. It is similar to List, but it keeps only non-duplicate elements and has no concept of ordering.

Set & MutableSet

Set is an interface that supports read-only access.

interface Set<out E> : Collection<E>

MutableSet provides operations for adding and removing elements.

interface MutableSet<E> : Set<E>, MutableCollection<E>

Creating a Set (setOf)

An immutable set can be created with Kotlin’s built-in setOf function.

fun main() {
    var s = setOf("Red", "Green", "Blue")
    println(s)
}

Output:

[Red, Green, Blue]

As a simple example, let’s create a mutable Set. If you want to add or remove elements after creating a Set, you must create the set with the mutableSetOf function.

val set: MutableSet<Int> = mutableSetOf(1, 2, 3)
set.add(1)
set.add(4)
println(set)

Output:

[1, 2, 3, 4]

Duplicate Elements in Set

Let’s put duplicate values into a Set.

val set: Set<Int> = setOf(1, 2, 3, 1, 2)
println(set)

Output:

[1, 2, 3]

Because Set does not keep duplicate elements, only one each of 1 and 2 is stored.

Performing Set Operations

You can find unions or differences through operations such as + and - on Set objects.

Union

You can use the + operator or the union() function to find the union between sets (a set made up of elements included in both sets). Because union() is defined as an infix function, it can be used like an operator.

val s1 = setOf(1, 2, 3, 4)
val s2 = setOf(3, 4, 5, 6)

println(s1 + s2) // [1, 2, 3, 4, 5, 6]
println(s1 union s2) // Same
println(s1.union(s2)) // Same

Intersection

With the intersect function, you can find the intersection of two Sets (a set made up of elements included in both sets). Because intersect() is defined as an infix function, it can be used like an operator.

val s1 = setOf(1, 2, 3, 4)
val s2 = setOf(3, 4, 5, 6)

println(s1 intersect s2) // [3, 4]
println(s1.intersect(s2)) // Same

Difference

You can use the - operator, the minus() function, or the subtract() function to find the difference between two Sets (a set made up only of elements that exist in the set specified on the left). Because subtract() is defined as an infix function, it can be used like an operator.

val s1 = setOf(1, 2, 3, 4)
val s2 = setOf(3, 4, 5, 6)

println(s1 - s2) // [1, 2].
println(s1.minus(s2)) // Same
println(s1 subtract s2) // Same
println(s1.subtract(s2)) // Same

Note that the result changes if you swap the values on the left and right sides of a difference operation.

println(s1 - s2) // [1, 2].
println(s2 - s1) // [5, 6].