Kotlin Program to Convert Array to Set (HashSet) and Vice-Versa

Example 1: Convert Array to Set

import java.util.*

fun main(args: Array<String>) {

    val array = arrayOf("a", "b", "c")
    val set = HashSet(Arrays.asList(*array))

    println("Set: $set")

}

When you run the program, the output will be:

Set: [a, b, c]

In the above program, we've an array named array. To convert array to set, we first convert it to a list using asList() as HashSet accepts list as a constructor.

Then, we initialize set with the elements of the converted list.


Example 2: Convert Set to Array

import java.util.*

fun main(args: Array<String>) {

    val set = HashSet<String>()
    set.add("a")
    set.add("b")
    set.add("c")

    val array = arrayOfNulls<String>(set.size)
    set.toArray(array)

    println("Array: ${Arrays.toString(array)}")

}

When you run the program, the output will be:

Array: [a, b, c]

In the above program, we've a HashSet named set. To convert set into an array, we first create an array of length equal to the size of the set and use toArray() method.

Here's the equivalent Java code: Java program to convert array into a set and vice-versa.

Did you find this article helpful?