Open In App

Kotlin hashSetOf()

Improve
Improve
Like Article
Like
Save
Share
Report

Kotlin HashSet is a generic unordered collection of elements and it does not contain duplicate elements. It implements the set interface. hashSetOf() is a function that returns a mutable hashSet, which can be both read and written. The HashSet class store all the elements using the hashing mechanism.

Syntax:

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

It returns a new HashSet with the given elements but does not guarantee the order sequence specified at the storing time.

Example of hashSetOf()  

Kotlin




fun main(args: Array<String>)
{
  
    //declaring a hash set of integers
    val seta = hashSetOf(1,2,3,3);
    //printing first set
    println(seta)
      
    //declaring a hash set of strings
    val setb = hashSetOf("Geeks","for","geeks");
    println(setb);
      
}


Output: 

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

Adding and removing elements in hashset –

  • We can add elements in a hashset using add() and addAll() functions.
  • We can remove an element using remove() function.

Kotlin program of using the add() and remove() method:

Kotlin




fun main(args: Array<String>)
{
    //declaring a hash set of integers
    val seta = hashSetOf<Int>();
    println(seta)
  
    //adding elements
    seta.add(1)
    seta.add(2)
  
    //making an extra set to add it in seta
    val newset = setOf(4,5,6)
    seta.addAll(newset)
  
    println(seta)
  
    //removing 2 from the set
    seta.remove(2)
    println(seta)    
}


Output: 

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

Traversal in hashSet-

We can traverse a hashSet using an iterator in a loop.

Kotlin




fun main(args: Array<String>)
{
    //declaring a hash set of integers
    val seta = hashSetOf(1,2,3,5);
      
    //traversing in a set using a for loop
    for(item in seta)
        println(item)
}


Output: 

1
2
3
5

HashSet Indexing –

Using index functions indexOf() , lastIndexOf() we can get the index of the specified element. And we can also find the elements at some specific index using elementAt() function.

Kotlin program of using index –  

Kotlin




fun main(args: Array<String>) {
 
    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? 
Kotlin program of using contains() and containsAll() function – 

Kotlin




fun main(args: Array<String>){
    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 

Checking equality of empty hash sets and use of isEmpty() functions –

fun <T> hashSetOf(): hashSet<T>

This syntax returns an empty hash set of a specific type.
Kotlin program of using isEmpty() function – 

Kotlin




fun main(args: Array<String>) {
    //creating an empty hash set of strings
    val seta = hashSetOf<String>()
    //creating an empty hashset of integers
    val setb =hashSetOf<Int>()
 
 
    //checking if set is empty or not
    println("seta.isEmpty() is ${seta.isEmpty()}")
 
    // Since Empty hashsets are equal
 
    //checking if two hash sets are equal or not
    println("seta == setb is ${seta == setb}")
}


Output : 

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

 hashSetOf() is a function in Kotlin that creates a new hash set. A hash set is an unordered collection of unique elements that provides constant time performance for adding, removing, and checking the presence of an element.

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

Kotlin




fun main() {
    // create a new hash set
    val numbers = hashSetOf(1, 2, 3)
 
    // add a new element to the set
    numbers.add(4)
 
    // remove an element from the set
    numbers.remove(2)
 
    // check if the set contains an element
    val containsFive = numbers.contains(5)
 
    // print the set and the result of the contains check
    println("Numbers: $numbers")
    println("Contains 5: $containsFive")
}


Output:

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

In this example, we create a new hash set 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.


Last Updated : 14 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads