Kotlin Array.toHashSet() Tutorial
The Array.toHashSet()
function in Kotlin is used to convert an Array to a HashSet. It creates a new hash set containing the distinct elements of the original array.
Array.toHashSet() function is useful when you want to eliminate duplicate elements and work with a collection of unique values in your Kotlin code.
This tutorial will explore the syntax of the Array.toHashSet()
function and provide examples of its usage in Kotlin arrays.
Syntax
The syntax of the Array.toHashSet()
function is as follows:
fun <T> Array<out T>.toHashSet(): HashSet<T>
Examples for Array.toHashSet() function
1. Convert given Array of integers to a HashSet
In this example, we’ll take an Array of integer in numbersArray
, and use toHashSet()
to convert the given array to a hash set.
Kotlin Program
fun main() {
val numbersArray = arrayOf(1, 2, 3, 2, 4, 5, 4, 6, 7, 8, 9)
// Using toHashSet() to convert the array of integers to a hash set
val uniqueNumbersHashSet = numbersArray.toHashSet()
// Printing the original array and the resulting hash set
println("Input Array:\n${numbersArray.contentToString()}\n")
println("Output HashSet:\n$uniqueNumbersHashSet")
}
Output
Input Array:
[1, 2, 3, 2, 4, 5, 4, 6, 7, 8, 9]
Output HashSet:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Summary
In this tutorial, we’ve covered the Array.toHashSet()
function in Kotlin, its syntax, and how to use it to convert an array to a hash set.