Clear All Elements from HashSet in Kotlin | Kotlin HashSet clear Function

The clear function in Kotlin is used to remove all elements from a HashSet. This function is part of the Kotlin standard library and provides a convenient way to empty a set.

Table of Contents

  1. Introduction
  2. clear Function Syntax
  3. Understanding clear
  4. Examples
    • Basic Usage
    • Checking If Set Is Empty After Clearing
  5. Real-World Use Case
  6. Conclusion

Introduction

The clear function allows you to remove all elements from a HashSet, leaving it empty. This is useful for scenarios where you need to reset or reuse a set without creating a new instance.

clear Function Syntax

The syntax for the clear function is as follows:

fun clear()

Parameters:

  • This function does not take any parameters.

Returns:

  • This function does not return any value.

Understanding clear

The clear function removes all elements from the HashSet, resulting in an empty set. The size of the set after calling clear will be 0.

Examples

Basic Usage

To demonstrate the basic usage of clear, we will create a HashSet, add some elements, and then clear the set.

Example

fun main() {
    val set = hashSetOf("Apple", "Banana", "Cherry")
    println("Original set: $set")

    set.clear()
    println("Set after clear: $set")
}

Output:

Original set: [Apple, Banana, Cherry]
Set after clear: []

Checking If Set Is Empty After Clearing

This example shows how to check if a HashSet is empty after calling the clear function.

Example

fun main() {
    val numbers = hashSetOf(1, 2, 3, 4, 5)
    println("Original set: $numbers")

    numbers.clear()
    println("Is the set empty after clear? ${numbers.isEmpty()}")
}

Output:

Original set: [1, 2, 3, 4, 5]
Is the set empty after clear? true

Real-World Use Case

Resetting a Set of Active Users

In real-world applications, the clear function can be used to reset a set of active users, allowing you to start fresh without creating a new set instance.

Example

fun main() {
    val activeUsers = hashSetOf("user1", "user2", "user3")
    println("Active users: $activeUsers")

    // Reset active users
    activeUsers.clear()
    println("Active users after clear: $activeUsers")
}

Output:

Active users: [user1, user2, user3]
Active users after clear: []

Conclusion

The clear function in Kotlin is a simple and effective way to remove all elements from a HashSet. It allows you to reset or reuse a set without creating a new instance, making it useful for various applications, including data management and session handling. 

By understanding and using the clear function, you can effectively manage and manipulate HashSet collections in your Kotlin applications.

Comments