Kotlin Set minusElement()
Syntax & Examples


Set.minusElement() extension function

The minusElement() extension function in Kotlin returns a set containing all elements of the original set except the specified element. It also works with collections, returning a list containing all elements of the original collection without the first occurrence of the specified element.


Syntax of Set.minusElement()

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

fun <T> Set<T>.minusElement(element: T): Set<T>

This minusElement() extension function of Set returns a set containing all elements of the original set except the given element.

Parameters

ParameterOptional/RequiredDescription
elementrequiredThe element to be removed from the set or collection.

Return Type

Set.minusElement() returns value of type Set.



✐ Examples

1 Removing an element from a set of integers

Using minusElement() to remove an element from a set of integers.

For example,

  1. Create a set of integers.
  2. Use minusElement() to remove an element from the set.
  3. Print the resulting set.

Kotlin Program

fun main() {
    val numbers = setOf(1, 2, 3, 4, 5)
    val result = numbers.minusElement(3)
    println(result)
}

Output

[1, 2, 4, 5]

2 Removing an element from a set of strings

Using minusElement() to remove an element from a set of strings.

For example,

  1. Create a set of strings.
  2. Use minusElement() to remove an element from the set.
  3. Print the resulting set.

Kotlin Program

fun main() {
    val strings = setOf("one", "two", "three")
    val result = strings.minusElement("two")
    println(result)
}

Output

[one, three]

3 Removing an element from a set of custom objects

Using minusElement() to remove an element from a set of custom objects.

For example,

  1. Create a data class.
  2. Create a set of custom objects.
  3. Use minusElement() to remove an object from the set.
  4. 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 result = people.minusElement(Person("Bob", 25))
    println(result)
}

Output

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

Summary

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