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.
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.
Parameter | Optional/Required | Description |
---|---|---|
element | required | The element to be removed from the set or collection. |
Set.minusElement() returns value of type Set
.
Using minusElement() to remove an element from a set of integers.
For example,
fun main() {
val numbers = setOf(1, 2, 3, 4, 5)
val result = numbers.minusElement(3)
println(result)
}
[1, 2, 4, 5]
Using minusElement() to remove an element from a set of strings.
For example,
fun main() {
val strings = setOf("one", "two", "three")
val result = strings.minusElement("two")
println(result)
}
[one, three]
Using minusElement() to remove an element from a set of custom objects.
For example,
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)
}
[Person(name=Alice, age=30), Person(name=Charlie, age=35)]
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.