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