diff --git a/core-kotlin-modules/core-kotlin-collections/src/main/kotlin/com/baeldung/collections/ListExample.kt b/core-kotlin-modules/core-kotlin-collections/src/main/kotlin/com/baeldung/collections/ListExample.kt index 38391a1049..10450cf84f 100644 --- a/core-kotlin-modules/core-kotlin-collections/src/main/kotlin/com/baeldung/collections/ListExample.kt +++ b/core-kotlin-modules/core-kotlin-collections/src/main/kotlin/com/baeldung/collections/ListExample.kt @@ -17,23 +17,45 @@ class ListExample { return cityList } - fun iterateUsingForLoop() { - countries.forEach { it -> print("$it ") } - println() + fun iterateUsingForEachLoop(): List { + val countryLength = mutableListOf() + countries.forEach { it -> + print("$it ") + println(" Length: ${it.length}") + countryLength.add(it.length) + } + return countryLength + } + fun iterateUsingForLoop(): List { + val countryLength = mutableListOf() for (country in countries) { print("$country ") + println(" Length: ${country.length}") + countryLength.add(country.length) } - println() + return countryLength + } + fun iterateUsingForLoopRange(): List { + val countryLength = mutableListOf() 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 { + val countryLength = mutableListOf() countries.forEachIndexed { i, e -> println("country[$i] = $e") + print(" Index: $i") + println(" Length: ${e.length}") + countryLength.add(e.length) } + return countryLength } fun iterateUsingListIterator() { diff --git a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/ListExampleUnitTest.kt b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/ListExampleUnitTest.kt index 541c5fd64f..195a0cf52a 100644 --- a/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/ListExampleUnitTest.kt +++ b/core-kotlin-modules/core-kotlin-collections/src/test/kotlin/com/baeldung/collections/ListExampleUnitTest.kt @@ -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())