Reference Materials
Certification Courses
Created with over a decade of experience and thousands of feedback.
Python online compiler
JavaScript online compiler
SQL online compiler
Java online compiler
HTML online compiler
C online compiler
C++ online compiler
C# online compiler
PHP online compiler
Swift online compiler
Kotlin online compiler
TypeScript online compiler
Go online compiler
Rust online compiler
Scala online compiler
Dart online compiler
R online compiler
Ruby online compiler
Kotlin Program to Convert Array to Set (HashSet) and Vice-Versa
In this program, you'll learn to convert an array to a set and vice versa in Kotlin.
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?