1
+ package iterateListAndAddItem
2
+
3
+ import org.junit.jupiter.api.Test
4
+ import kotlin.test.assertEquals
5
+
6
+
7
+ fun byForEach (list : List <String >): List <String > {
8
+ val result = mutableListOf<String >()
9
+ list.forEach {
10
+ result + = it
11
+ if (it.length > 1 ) {
12
+ result + = " <- a long one"
13
+ }
14
+ }
15
+ return result.toList()
16
+ }
17
+
18
+ fun byBuildList (list : List <String >) =
19
+ buildList {
20
+ list.forEach {
21
+ this + = it
22
+ if (it.length > 1 ) {
23
+ this + = " <- a long one"
24
+ }
25
+ }
26
+ }
27
+
28
+ fun addBeforeByBuildList (list : List <String >) =
29
+ buildList {
30
+ list.forEach {
31
+ if (it.length > 1 ) {
32
+ this + = " a long one ->"
33
+ }
34
+ this + = it
35
+ }
36
+ }
37
+
38
+ fun byListIterator (list : MutableList <String >) {
39
+ val it = list.listIterator()
40
+ for (e in it) {
41
+ if (e.length > 1 ) {
42
+ it.add(" <- a long one" )
43
+ }
44
+ }
45
+ }
46
+
47
+ fun addBeforeByListIterator (list : MutableList <String >) {
48
+ val it = list.listIterator()
49
+ for (e in it) {
50
+ if (e.length > 1 ) {
51
+ it.previous()
52
+ it.add(" a long one ->" )
53
+ it.next()
54
+ }
55
+ }
56
+ }
57
+
58
+ class IterateListAndAddElementUnitTest {
59
+ val myList = listOf (" ab" , " a" , " cd" , " c" , " xyz" )
60
+
61
+ @Test
62
+ fun `when using byLoop() then get expected result` () {
63
+ assertEquals(
64
+ listOf (" ab" , " <- a long one" , " a" , " cd" , " <- a long one" , " c" , " xyz" , " <- a long one" ),
65
+ byForEach(myList)
66
+ )
67
+ }
68
+
69
+ @Test
70
+ fun `when using buildList() then get expected result` () {
71
+ assertEquals(
72
+ listOf (" ab" , " <- a long one" , " a" , " cd" , " <- a long one" , " c" , " xyz" , " <- a long one" ),
73
+ byBuildList(myList)
74
+ )
75
+ // insert before the target
76
+ assertEquals(
77
+ listOf (" a long one ->" , " ab" , " a" , " a long one ->" , " cd" , " c" , " a long one ->" , " xyz" ),
78
+ addBeforeByBuildList(myList)
79
+ )
80
+ }
81
+
82
+ @Test
83
+ fun `given mutableList, when using listIterator to append elements then get expected result` () {
84
+ val myMutableList = mutableListOf (" ab" , " a" , " cd" , " c" , " xyz" )
85
+ byListIterator(myMutableList)
86
+ assertEquals(
87
+ listOf (" ab" , " <- a long one" , " a" , " cd" , " <- a long one" , " c" , " xyz" , " <- a long one" ),
88
+ myMutableList
89
+ )
90
+ }
91
+
92
+ @Test
93
+ fun `given mutableList, when using listIterator to prepend elements then get expected result` () {
94
+ val myMutableList = mutableListOf (" ab" , " a" , " cd" , " c" , " xyz" )
95
+ addBeforeByListIterator(myMutableList)
96
+ assertEquals(
97
+ listOf (" a long one ->" , " ab" , " a" , " a long one ->" , " cd" , " c" , " a long one ->" , " xyz" ),
98
+ myMutableList
99
+ )
100
+ }
101
+ }
0 commit comments