5

I have an array of String

val array = arrayOf("a", "b", "c")

I need to convert it to HashSet

val set = HashSet<String>()
Gibolt
  • 42,564
  • 15
  • 187
  • 127
Anisuzzaman Babla
  • 6,510
  • 7
  • 36
  • 53

3 Answers3

8

Use extension function toHashSet as follow

array.toHashSet()

That function belongs to Kotlin Library

/**
 * Returns a [HashSet] of all elements.
 */
public fun <T> Array<out T>.toHashSet(): HashSet<T> {
    return toCollection(HashSet<T>(mapCapacity(size)))
}
Abner Escócio
  • 2,697
  • 2
  • 17
  • 36
0

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]
Anisuzzaman Babla
  • 6,510
  • 7
  • 36
  • 53
0

Kotlin Collections Solution

Directly use toSet(*array) or toHashSet(*array). These are part of Kotlin's standard library.

The asterisk * is the spread operator. It applies all elements in a collection individually, each passed in order to a vararg method parameter.

val array = arrayOf("data", "foo")

// Multiple spreads ["data", "foo", "bar", "data", "foo"]
val mySet = setOf(*array, "bar", *array)

Passing no parameters setOf() results in an empty set.

These are all of the specific hash types you can use:

setOf()
hashSetOf()
linkedSetOf()
mutableSetOf()
sortableSetOf()

This is how to define the collection item type explicitly.

setOf<String>()
hashSetOf<MyClass>()
Gibolt
  • 42,564
  • 15
  • 187
  • 127