Skip to main content

How to remove elements from a HashSet in Kotlin

How to remove elements from a HashSet in Kotlin.

Here's a step-by-step tutorial on how to remove elements from a HashSet in Kotlin.

Step 1: Create a HashSet

First, let's create a HashSet and populate it with some elements. A HashSet is an unordered collection that does not allow duplicate values.

val set = HashSet<String>()
set.add("Apple")
set.add("Banana")
set.add("Orange")
set.add("Grapes")

In this example, we have created a HashSet of type String and added four fruits to it.

Step 2: Remove an Element by Value

To remove an element from a HashSet based on its value, you can use the remove() function. This function takes the value of the element you want to remove and returns true if the element was found and removed successfully, or false if the element was not found in the HashSet.

val removed = set.remove("Apple")
if (removed) {
println("Element 'Apple' removed successfully")
} else {
println("Element 'Apple' not found")
}

In this example, we are removing the element with the value "Apple" from the HashSet. If the removal is successful, we print a success message. Otherwise, we print a message indicating that the element was not found.

Step 3: Remove an Element by Index

Unlike other collection types, HashSet does not provide direct access to its elements by index. Therefore, you cannot remove an element from a HashSet by index. Instead, you must remove it by its value using the remove() function as shown in Step 2.

Step 4: Remove Multiple Elements

To remove multiple elements from a HashSet, you can use the removeAll() function. This function takes another collection as an argument and removes all the elements that are present in both the HashSet and the given collection.

val fruitsToRemove = setOf("Banana", "Grapes")
set.removeAll(fruitsToRemove)

In this example, we have created a set of fruits to remove, which includes "Banana" and "Grapes". We then use the removeAll() function to remove these fruits from the HashSet.

Step 5: Clear the HashSet

If you want to remove all elements from a HashSet, you can use the clear() function. This function removes all elements from the HashSet, leaving it empty.

set.clear()

In this example, we simply call the clear() function to remove all elements from the HashSet.

That's it! You have learned how to remove elements from a HashSet in Kotlin. Whether you want to remove elements by value, remove multiple elements, or clear the entire HashSet, these steps should help you accomplish your goal.