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 Data Types
- Hello World program in Kotlin
- Kotlin | Retrieve Collection Parts
- Destructuring Declarations in Kotlin
- DatePicker in Kotlin
- Kotlin labeled continue
- Introduction to Kotlin
- Kotlin Type Conversion
- Kotlin Exception Handling | try, catch, throw and finally
- Kotlin if-else expression
- Kotlin Environment setup for Command Line
- Kotlin constructor
- Kotlin Environment setup with Intellij IDEA
- Kotlin Nested class and Inner class
- Kotlin Variables
- Kotlin Operators
- Kotlin Standard Input/Output
- Kotlin Expression, Statement and Block
- Kotlin when expression
- Kotlin for loop
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.