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 which returns a mutable hashSet, which can be both read and written. The HashSet class store all the elements using hashing mechanism.
fun <T> hashSetOf(vararg elements: T): HashSet<T>
It returns a new HashSet with the given elements but does not guarantees about the order sequence specified at the storing time.
Example of hashSetOf()
[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 –
 [1, 2, 4, 5, 6] [1, 4, 5, 6]
Traversal in hashSet-
We can traverse a hashSet using an iterator in a loop.
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 –
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 –
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 specific type.
Kotlin program of using isEmpty() function –
seta.isEmpty() is true seta == setb is true
- Kotlin Set : setOf()
- Kotlin | apply vs with
- Kotlin Ranges
- Kotlin Map : mapOf()
- Kotlin Hashmap
- Triple in Kotlin
- Pair in Kotlin
- Kotlin Reflection
- Kotlin Array
- Kotlin String
- HorizontalScrollView in Kotlin
- Kotlin Collections
- Comparator in Kotlin
- Notifications in Kotlin
- RatingBar in Kotlin
- Chronometer in Kotlin
- SeekBar in Kotlin
- CheckedTextView in Kotlin
- Switch in Kotlin
- Button in Kotlin
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.