Skip to content

Commit 26b119f

Browse files
[KTLN-713] Remove Null and Empty Values from a List in Kotlin (#757)
* fixed Unit test * code cleanup
1 parent 90ebe0b commit 26b119f

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package removeNullAndEmptyValues
2+
3+
import org.junit.jupiter.api.Assertions.assertEquals
4+
import org.junit.jupiter.api.Test
5+
6+
class RemoveNullAndEmptyValuesUnitTest {
7+
8+
@Test
9+
fun `remove null and empty values from list via list iteration`() {
10+
val listWithNullsAndEmpty: MutableList<String?> = mutableListOf("A", null, "", "C", null, "E")
11+
val listWithoutNullsAndEmpty = removeValuesViaIteration(listWithNullsAndEmpty)
12+
assertEquals(listOf("A", "C", "E"), listWithoutNullsAndEmpty)
13+
}
14+
15+
@Test
16+
fun `remove null and empty values from list using filterNotNull and filterNot methods`() {
17+
val listWithNullsAndEmpty: List<String?> = listOf("A", null, "", "C", null, "E")
18+
val listWithoutNulls: List<String> = listWithNullsAndEmpty.filterNotNull()
19+
20+
val listWithoutNullsAndEmpty: List<String> = listWithoutNulls.filterNot { it.isEmpty() }
21+
22+
assertEquals(listOf("A", "", "C", "E"), listWithoutNulls)
23+
assertEquals(listOf("A", "C", "E"), listWithoutNullsAndEmpty)
24+
}
25+
26+
@Test
27+
fun `remove null and empty values from list using removeIf method`() {
28+
val listWithNullsAndEmpty: MutableList<String?> = mutableListOf("A", null, "", "C", null, "E")
29+
listWithNullsAndEmpty.removeIf { it == null || it.isEmpty() }
30+
31+
assertEquals(listOf("A", "C", "E"), listWithNullsAndEmpty)
32+
}
33+
34+
fun removeValuesViaIteration(listWithNullsAndEmpty: MutableList<String?>): List<String> {
35+
val iterator = listWithNullsAndEmpty.iterator()
36+
while (iterator.hasNext()) {
37+
val element = iterator.next()
38+
if (element == null || element.isEmpty()) {
39+
iterator.remove()
40+
}
41+
}
42+
return listWithNullsAndEmpty as List<String>
43+
}
44+
}

0 commit comments

Comments
 (0)