The remove
method of the HashSet
class can be used to remove the specific element from the set
.
fun remove(element: E): Boolean
The method takes the element to be removed from the HashSet
object as an argument.
This method returns true
if the passed argument is removed from the set
. If the element is not present in the set
, then false
is returned.
The below code demonstrates how to use the remove
method:
fun main() {//create a new HashSet which can have integer type as elementsvar set: HashSet<Int> = hashSetOf<Int>()// add three entriesset.add(1)set.add(2)set.add(3)println("\nThe set is : $set")println("\nset.remove(1):" + set.remove(1))println("The set is : $set")println("\nset.remove(5):" + set.remove(5))println("The set is : $set")}
In the above code, we see the following:
Line 3: We create a new HashSet
object with the name set
. We use the hashSetOf()
method to create an empty HashSet
.
Lines 6 to 8: We add three new elements, (1,2,3)
, to the set
using the add()
method.
Line 11: We use the remove
method of the set
object to remove the element 1
. The element 1
is present in the set. The element 1
is removed and true
is returned as result. Now the set
is [2,3]
.
Line 15: We use the remove
method of the set
object to remove the element 5
. The element 5
is not present in the set
. So, false
is returned and set
remains unchanged.