Skip to content

Commit e60b34f

Browse files
yadavan88fabiotadashi
authored andcommitted
Code to convert between array and set
1 parent 614ac20 commit e60b34f

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package com.baeldung.arraytoset
2+
3+
import org.junit.Test
4+
import kotlin.test.assertEquals
5+
6+
class ArrayToSetUnitTest {
7+
@Test
8+
fun `convert array to set using toSet`() {
9+
val arr = arrayOf(1, 5, 2, 4, 1)
10+
val set = arr.toSet()
11+
assertEquals(setOf(1, 5, 2, 4), set)
12+
}
13+
14+
@Test
15+
fun `convert array to set using setOf`() {
16+
val arr = arrayOf(1, 5, 2, 4, 1)
17+
val set = setOf(*arr)
18+
assertEquals(setOf(1, 5, 2, 4), set)
19+
}
20+
21+
@Test
22+
fun `convert array to set using HashSet`() {
23+
val arr = arrayOf(1, 5, 2, 4, 1)
24+
val set = HashSet(arr.toList())
25+
assertEquals(setOf(1, 5, 2, 4), set)
26+
}
27+
28+
@Test
29+
fun `convert array to set using loop`() {
30+
val arr = arrayOf(1, 5, 2, 4, 1)
31+
val mutableSet = mutableSetOf<Int>()
32+
for (i in arr) {
33+
mutableSet.add(i)
34+
}
35+
assertEquals(setOf(1, 5, 2, 4), mutableSet)
36+
}
37+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package com.baeldung.settoarray
2+
3+
import org.junit.Test
4+
import org.junit.jupiter.api.Assertions
5+
6+
class SetToArrayUnitTest {
7+
8+
@Test
9+
fun `convert set to array using toTypedArray`() {
10+
val set = setOf(1, 2, 3, 4)
11+
val arr = set.toTypedArray()
12+
Assertions.assertArrayEquals(arrayOf(1, 2, 3, 4), arr)
13+
}
14+
15+
@Test
16+
fun `convert set to array using Array constructor`() {
17+
val set = setOf(1, 2, 3, 4)
18+
val arr = Array(set.size) { set.elementAt(it) }
19+
Assertions.assertArrayEquals(arrayOf(1, 2, 3, 4), arr)
20+
}
21+
}

0 commit comments

Comments
 (0)