Refactored the for loop implementation
This commit is contained in:
parent
91c2a7a4d5
commit
71262e5e55
|
@ -17,23 +17,45 @@ class ListExample {
|
|||
return cityList
|
||||
}
|
||||
|
||||
fun iterateUsingForLoop() {
|
||||
countries.forEach { it -> print("$it ") }
|
||||
println()
|
||||
fun iterateUsingForEachLoop(): List<Int> {
|
||||
val countryLength = mutableListOf<Int>()
|
||||
countries.forEach { it ->
|
||||
print("$it ")
|
||||
println(" Length: ${it.length}")
|
||||
countryLength.add(it.length)
|
||||
}
|
||||
return countryLength
|
||||
}
|
||||
|
||||
fun iterateUsingForLoop(): List<Int> {
|
||||
val countryLength = mutableListOf<Int>()
|
||||
for (country in countries) {
|
||||
print("$country ")
|
||||
println(" Length: ${country.length}")
|
||||
countryLength.add(country.length)
|
||||
}
|
||||
return countryLength
|
||||
}
|
||||
println()
|
||||
|
||||
fun iterateUsingForLoopRange(): List<Int> {
|
||||
val countryLength = mutableListOf<Int>()
|
||||
for (i in 0 until countries.size) {
|
||||
print("${countries[i]} ")
|
||||
println(" Length: ${countries[i].length}")
|
||||
countryLength.add(countries[i].length)
|
||||
}
|
||||
return countryLength
|
||||
}
|
||||
println()
|
||||
|
||||
fun iterateUsingForEachIndexedLoop(): List<Int> {
|
||||
val countryLength = mutableListOf<Int>()
|
||||
countries.forEachIndexed { i, e ->
|
||||
println("country[$i] = $e")
|
||||
print(" Index: $i")
|
||||
println(" Length: ${e.length}")
|
||||
countryLength.add(e.length)
|
||||
}
|
||||
return countryLength
|
||||
}
|
||||
|
||||
fun iterateUsingListIterator() {
|
||||
|
|
|
@ -17,6 +17,26 @@ class ListExampleUnitTest {
|
|||
assertTrue(classUnderTest.createMutableList().contains("Seoul"))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenIterateUsingForEachLoop_thenSuccess() {
|
||||
assertEquals(7, classUnderTest.iterateUsingForEachLoop()[0])
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenIterateUsingForLoop_thenSuccess() {
|
||||
assertEquals(5, classUnderTest.iterateUsingForLoop()[1])
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenIterateUsingForLoopRange_thenSuccess() {
|
||||
assertEquals(6, classUnderTest.iterateUsingForLoopRange()[3])
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenIterateUsingForEachIndexedLoop_thenSuccess() {
|
||||
assertEquals(9, classUnderTest.iterateUsingForEachIndexedLoop()[4])
|
||||
}
|
||||
|
||||
@Test
|
||||
fun whenRetrieveElementsInList_thenSuccess() {
|
||||
assertEquals("Japan", classUnderTest.retrieveElementsInList())
|
||||
|
|
Loading…
Reference in New Issue