![]() |
VOOZH | about |
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()
Output:
[1, 2, 3]
[Geeks, for, geeks]
We can use:
Example of using the add() and remove() method:
Output:
[]
[1, 2, 4, 5, 6]
[1, 4, 5, 6]
A HashSet can be traversed using an iterator or in a for loop:
Output:
1
2
3
5
Although a HashSet is unordered, we can use the following functions for indexing:
Example of using index –
Output:
The element at index 2 is: Malinga
The index of element is: 4
The last index of element is: 0
Both the methods are used to check whether an element is present in the Hashset or not?
Example of using contains() and containsAll() function –
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
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 -
Output :
seta.isEmpty() is true
seta == setb is true
Here's an example of using hashSetOf() to create a set of integers:
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.