How to use the remove method of the HashSet in Kotlin
Overview
The remove method of the HashSet class can be used to remove the specific element from the set.
Syntax
fun remove(element: E): Boolean
Parameter
The method takes the element to be removed from the HashSet object as an argument.
Return value
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.
Code example
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")}
Explanation
In the above code, we see the following:
-
Line 3: We create a new
HashSetobject with the nameset. We use thehashSetOf()method to create an emptyHashSet. -
Lines 6 to 8: We add three new elements,
(1,2,3), to thesetusing theadd()method. -
Line 11: We use the
removemethod of thesetobject to remove the element1. The element1is present in the set. The element1is removed andtrueis returned as result. Now thesetis[2,3]. -
Line 15: We use the
removemethod of thesetobject to remove the element5. The element5is not present in theset. So,falseis returned andsetremains unchanged.