Kotlin Tutorials

Kotlin Set subtract()
Syntax & Examples

Set.subtract() extension function

The subtract() extension function in Kotlin returns a set containing all elements that are contained by this collection and not contained by the specified collection.


Syntax of Set.subtract()

The syntax of Set.subtract() extension function is:

infix fun <T> Set<T>.subtract(other: Iterable<T>): Set<T>

This subtract() extension function of Set returns a set containing all elements that are contained by this collection and not contained by the specified collection.

Parameters

ParameterOptional/RequiredDescription
otherrequiredThe collection of elements to be subtracted from the original set.

Return Type

Set.subtract() returns value of type Set.



✐ Examples

1 Subtracting elements from a set of integers

Using subtract() to subtract elements from a set of integers.

For example,

  1. Create a set of integers.
  2. Create another collection of integers to be subtracted.
  3. Use subtract() to get the difference between the sets.
  4. Print the resulting set.

Kotlin Program

fun main() {
    val numbers = setOf(1, 2, 3, 4, 5)
    val toSubtract = listOf(2, 4)
    val result = numbers subtract toSubtract
    println(result)
}

Output

[1, 3, 5]

2 Subtracting elements from a set of strings

Using subtract() to subtract elements from a set of strings.

For example,

  1. Create a set of strings.
  2. Create another collection of strings to be subtracted.
  3. Use subtract() to get the difference between the sets.
  4. Print the resulting set.

Kotlin Program

fun main() {
    val strings = setOf("one", "two", "three")
    val toSubtract = listOf("two")
    val result = strings subtract toSubtract
    println(result)
}

Output

[one, three]

3 Subtracting elements from a set of custom objects

Using subtract() to subtract elements from a set of custom objects.

For example,

  1. Create a data class.
  2. Create a set of custom objects.
  3. Create another collection of custom objects to be subtracted.
  4. Use subtract() to get the difference between the sets.
  5. Print the resulting set.

Kotlin Program

data class Person(val name: String, val age: Int)

fun main() {
    val people = setOf(Person("Alice", 30), Person("Bob", 25), Person("Charlie", 35))
    val toSubtract = listOf(Person("Bob", 25))
    val result = people subtract toSubtract
    println(result)
}

Output

[Person(name=Alice, age=30), Person(name=Charlie, age=35)]

Summary

In this Kotlin tutorial, we learned about subtract() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.