Refactored the for loop implementation

This commit is contained in:
Anirban Chatterjee 2020-06-12 23:20:17 +02:00
parent 91c2a7a4d5
commit 71262e5e55
2 changed files with 47 additions and 5 deletions

View File

@ -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)
}
println()
return countryLength
}
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)
}
println()
return countryLength
}
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() {

View File

@ -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())