English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Kotlin program to convert an array to a Set (HashSet)

Comprehensive Collection of Kotlin Examples

In this program, you will learn how to convert an array to a collection in Kotlin.

Example1Convert an array to a collection

import java.util.*
fun main(args: Array<String>) {
    val array = arrayOf("a", "b", "c")
    val set = HashSet(Arrays.asList(*array))
    println("Set: $set")
}

When running the program, the output is:

Set: [a, b, c]

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

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

Example2Convert the set collection to an 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 running the program, the output is:

Array: [a, b, c]

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

The equivalent Java code is as follows:Java Program to Interconvert Array and Set.

Comprehensive Collection of Kotlin Examples