Open In App

Kotlin hashSetOf()

Last Updated : 25 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Kotlin, a HashSet is a generic, unordered collection that holds unique elements only. It does not allow duplicates and provides constant-time performance for basic operations like add, remove, and contains, thanks to its internal hashing mechanism. The hashSetOf() function in Kotlin creates a mutable HashSet that allows both read and write operations.

Syntax:

fun <T> hashSetOf(vararg elements: T): HashSet<T>

This function returns a new HashSet containing the provided elements. However, it does not guarantee any specific order of elements, even if inserted in a certain sequence.

Example of hashSetOf()  

Kotlin
fun main() {
    val numbers = hashSetOf(1, 2, 3)
    val words = hashSetOf("Geeks", "for", "geeks")
    println(numbers)
    println(words)
}

Output: 

[1, 2, 3]
[Geeks, for, geeks]

Adding and Removing elements in hashset -

We can use:

  1. add() to insert a single element.
  2. addAll() to add multiple elements.
  3. remove() to delete an element.

Example of using the add() and remove() method:

Kotlin
fun main() {
    val set = hashSetOf<Int>()
    println(set)
    
    set.addAll(listOf(1, 2, 4, 5, 6))
    println(set) 
    
    set.remove(2)
    println(set) 
}

Output: 

[]
[1, 2, 4, 5, 6]
[1, 4, 5, 6]

Traversing a HashSet-

A HashSet can be traversed using an iterator or in a for loop:

Kotlin
fun main() {
    val seta = hashSetOf(1,2,3,5);
     
    for(item in seta) {
        println(item)
    }
}

Output: 

1
2
3
5

HashSet Indexing –

Although a HashSet is unordered, we can use the following functions for indexing:

  1. elementAt(index) to get the element at a specific index.
  2. indexOf() and lastIndexOf() functions to get element positions.

Example of using index –  

Kotlin
fun main() {
    val captains = hashSetOf("Kohli","Smith","Root","Malinga","Rohit","Dhawan")
    println("The element at index 2 is: "+captains.elementAt(3))
    println("The index of element is: "+captains.indexOf("Smith"))
    println("The last index of element is: "+captains.lastIndexOf("Rohit"))
}

Output: 

The element at index 2 is: Malinga
The index of element is: 4
The last index of element is: 0

contains() and containsAll() functions –

Both the methods are used to check whether an element is present in the Hashset or not? 

Example of using contains() and containsAll() function – 

Kotlin
fun main(){
    val captains = hashSetOf(1,2,3,4,"Kohli","Smith","Root","Malinga","Rohit","Dhawan")

    var name = "Rohit"
    println("The set contains the element $name or not?" +"   "+captains.contains(name))

    var num = 5
    println("The set contains the element $num or not?" +"   "+captains.contains(num))

    println("The set contains the given elements or not?" +"   "+captains.containsAll(setOf(1,3,"Dhawan","Warner")))
}

Output: 

The set contains the element Rohit or not?   true
The set contains the element 5 or not? false
The set contains the given elements or not? false

Working with Empty Sets and isEmpty() -

val emptySet = hashSetOf<String>()

This syntax returns an empty hash set of a specific type. You can check if it's empty using isEmpty().

Example of using isEmpty() function - 

Kotlin
fun main() {
    val seta = hashSetOf<String>()
    val setb =hashSetOf<Int>()

    println("seta.isEmpty() is ${seta.isEmpty()}")
    println("seta == setb is ${seta == setb}")
}

Output : 

seta.isEmpty() is true
seta == setb is true

Full Example Demonstrating hashSetOf() -

Here's an example of using hashSetOf() to create a set of integers:

Kotlin
fun main() {
    val numbers = hashSetOf(1, 2, 3)
    numbers.add(4)
    numbers.remove(2)
    
    println("Numbers: $numbers")
    println("Contains 5: ${numbers.contains(5)}")
}

Output:

Numbers: [1, 3, 4]
Contains 5: false

In this example, we create a new hashset of integers using the hashSetOf() function and add three elements to it: 1, 2, and 3. We then add the element 4 to the set and remove 2 from the set. Finally, we check if the set contains the element 5 using the contains() function and print the result to the console.

Advantages of hashSetOf():

  1. The hash set data structure provides O(1) time complexity for adding, removing, and checking the presence of an element, making it very efficient for handling large sets of data.
  2. The hash set ensures that the elements are unique, so it is a good choice for keeping track of a collection of distinct values.
  3. The hashSetOf() function is easy to use and provides a simple way to create a new hash set with initial elements.

Disadvantages of hashSetOf():

  1. The order of elements in a hash set is not guaranteed, so the iteration order may not be the same as the insertion order.
  2. The performance of the hash set can degrade if the hash function produces many collisions, which can cause the set to become slower than other data structures such as an array or a linked list.

Next Article
Article Tags :

Similar Reads