Skip to content

Commit 2541789

Browse files
Merge pull request #741 from albertache1998/list-to-set
[KTLN-722] Add List Contents Into a Set in Kotlin
2 parents 25cd21e + aebf03e commit 2541789

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package com.baeldung.addListToSet
2+
3+
import org.junit.jupiter.api.Assertions.assertEquals
4+
import org.junit.jupiter.api.Test
5+
6+
class AddListContentToSetUnitTest {
7+
8+
@Test
9+
fun `test adding list contents to set programmatically`() {
10+
val list = listOf("apple", "banana", "orange")
11+
val set = addListToSet(list)
12+
assertEquals(setOf("apple", "banana", "orange"), set)
13+
}
14+
15+
@Test
16+
fun `test adding list contents to set using addAll() method`() {
17+
val list = listOf("apple", "banana", "orange")
18+
val set = mutableSetOf<String>()
19+
set.addAll(list)
20+
assertEquals(setOf("apple", "banana", "orange"), set)
21+
}
22+
23+
@Test
24+
fun `test adding list contents to set using toSet() method`() {
25+
val list = listOf("apple", "banana", "orange")
26+
val set = list.toSet()
27+
assertEquals(setOf("apple", "banana", "orange"), set)
28+
}
29+
30+
@Test
31+
fun `test adding list contents to set using plus operator`() {
32+
val set = setOf<String>()
33+
val list = listOf("apple", "banana", "orange")
34+
val newSet = set + list
35+
assertEquals(setOf("apple", "banana", "orange"), newSet)
36+
}
37+
38+
@Test
39+
fun `test adding list contents to set using union method`() {
40+
val set = setOf<String>()
41+
val list = listOf("apple", "banana", "orange")
42+
val newSet = set.union(list)
43+
assertEquals(setOf("apple", "banana", "orange"), newSet)
44+
}
45+
46+
fun addListToSet(list: List<String>): Set<String> {
47+
val set = mutableSetOf<String>()
48+
for (element in list) {
49+
set.add(element)
50+
}
51+
return set
52+
}
53+
}

0 commit comments

Comments
 (0)