1
+ package com.baeldung.skipNullListToMap
2
+
3
+ import org.junit.jupiter.api.Assertions.assertEquals
4
+ import org.junit.jupiter.api.Test
5
+
6
+ class SkipNullListToMapUnitTest {
7
+
8
+ @Test
9
+ fun `Skips null values using for loop` () {
10
+ val pairs = listOf<Pair <String , Int ?>>(Pair (" a" , 1 ), Pair (" b" , null ), Pair (" c" , 3 ))
11
+ val expected = mapOf (" a" to 1 , " c" to 3 )
12
+ val map = mutableMapOf<String , Int >()
13
+ for (pair in pairs) {
14
+ if (pair.second != null ) {
15
+ map[pair.first] = pair.second!!
16
+ }
17
+ }
18
+ assertEquals(expected, map)
19
+ }
20
+
21
+ @Test
22
+ fun `Skips null values using the filter method` () {
23
+ val list = listOf<Pair <String , Int ?>>(Pair (" a" , 1 ), Pair (" b" , null ), Pair (" c" , 3 ))
24
+ val filteredList = list.filter { it.second != null }
25
+ val map = filteredList.toMap()
26
+
27
+ val expected = mapOf (" a" to 1 , " c" to 3 )
28
+ assertEquals(expected, map)
29
+ }
30
+
31
+ @Test
32
+ fun `Skips null values using the mapNotNull method` () {
33
+ val pairs = listOf<Pair <String , Int ?>>(Pair (" a" , 1 ), Pair (" b" , null ), Pair (" c" , 3 ))
34
+ val expected = mapOf (" a" to 1 , " c" to 3 )
35
+ val result = pairs.mapNotNull { it.second?.let { value -> it.first to value } }.toMap()
36
+
37
+ assertEquals(expected, result)
38
+ }
39
+
40
+ @Test
41
+ fun `Skips null values using the fold method` () {
42
+ val pairs = listOf<Pair <String , Int ?>>(Pair (" a" , 1 ), Pair (" b" , null ), Pair (" c" , 3 ))
43
+ val expected = mapOf (" a" to 1 , " c" to 3 )
44
+ val map = pairs.fold(mutableMapOf<String , Int >()) { acc, pair ->
45
+ acc.apply {
46
+ if (pair.second != null ) {
47
+ put(pair.first, pair.second!! )
48
+ }
49
+ }
50
+ }
51
+ assertEquals(expected, map)
52
+ }
53
+ }
0 commit comments