Merge pull request #9436 from anirban99/feature/ktln-43/working-with-lists-in-kotlin

KTLN-43 : Working with lists in Kotlin
This commit is contained in:
Josh Cummings 2020-06-20 23:33:40 -06:00 committed by GitHub
commit 118786c62a
3 changed files with 332 additions and 1 deletions

View File

@ -0,0 +1,204 @@
package com.baeldung.kotlin.collections
import kotlin.collections.List
class ListExample {
private val countries = listOf("Germany", "India", "Japan", "Brazil", "Australia")
private val cities = mutableListOf("Berlin", "Calcutta", "Seoul", "Sao Paulo", "Sydney")
fun createList(): List<String> {
val countryList = listOf("Germany", "India", "Japan", "Brazil")
return countryList
}
fun createMutableList(): MutableList<String> {
val cityList = mutableListOf("Berlin", "Calcutta", "Seoul", "Sao Paulo")
return cityList
}
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
}
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
}
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() {
val iterator = countries.listIterator()
while (iterator.hasNext()) {
val country = iterator.next()
print("$country ")
}
println()
while (iterator.hasPrevious()) {
println("Index: ${iterator.previousIndex()}")
}
}
fun iterateUsingIterator() {
val iterator = cities.iterator()
iterator.next()
iterator.remove()
println(cities)
}
fun iterateUsingMutableListIterator() {
val iterator = cities.listIterator(1)
iterator.next()
iterator.add("London")
iterator.next()
iterator.set("Milan")
println(cities)
}
fun retrieveElementsInList(): String {
println(countries[2])
return countries[2]
}
fun retrieveElementsUsingGet(): String {
println(countries.get(3))
return countries.get(3)
}
fun retrieveElementsFirstAndLast(): String? {
println(countries.first())
println(countries.last())
println(countries.first { it.length > 7 })
println(countries.last { it.startsWith("J") })
println(countries.firstOrNull { it.length > 8 })
return countries.firstOrNull { it.length > 8 }
}
fun retrieveSubList(): List<String> {
val subList = countries.subList(1, 4)
println(subList)
return subList
}
fun retrieveListSliceUsingIndices(): List<String> {
val sliceList = countries.slice(1..4)
println(sliceList)
return sliceList
}
fun retrieveListSliceUsingIndicesList(): List<String> {
val sliceList = countries.slice(listOf(1, 4))
println(sliceList)
return sliceList
}
fun countList(): Int {
val count = countries.count()
println(count)
return count
}
fun countListUsingPredicate(): Int {
val count = countries.count { it.length > 5 }
println(count)
return count
}
fun countListUsingProperty(): Int {
val size = countries.size
println(size)
return size
}
fun addToList(): List<String> {
cities.add("Barcelona")
println(cities)
cities.add(3, "London")
println(cities)
cities.addAll(listOf("Singapore", "Moscow"))
println(cities)
cities.addAll(2, listOf("Prague", "Amsterdam"))
println(cities)
return cities
}
fun removeFromList(): List<String> {
cities.remove("Seoul")
println(cities)
cities.removeAt(1)
println(cities)
return cities
}
fun replaceFromList(): List<String> {
cities.set(3, "Prague")
println(cities)
cities[4] = "Moscow"
println(cities)
cities.fill("Barcelona")
println(cities)
return cities
}
fun sortMutableList(): List<String> {
cities.sort()
println(cities)
cities.sortDescending()
println(cities)
return cities
}
fun sortList(): List<String> {
val sortedCountries = countries.sorted()
println("countries = $countries")
println("sortedCountries = $sortedCountries")
val sortedCountriesDescending = countries.sortedDescending()
println("countries = $countries")
println("sortedCountriesDescending = $sortedCountriesDescending")
return sortedCountriesDescending
}
fun checkOneElementInList(): Boolean {
return countries.contains("Germany")
}
fun checkOneElementInListUsingOperator(): Boolean {
return "Spain" in countries
}
fun checkElementsInList(): Boolean {
return cities.containsAll(listOf("Calcutta", "Sao Paulo", "Sydney"))
}
}

View File

@ -0,0 +1,126 @@
package com.baeldung.kotlin.collections
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.Assertions.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class ListExampleUnitTest {
private val classUnderTest: ListExample = ListExample()
@Test
fun whenListIsCreated_thenContainsElements() {
assertTrue(classUnderTest.createList().contains("India"))
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())
}
@Test
fun whenRetrieveElementsUsingGet_thenSuccess() {
assertEquals("Brazil", classUnderTest.retrieveElementsUsingGet())
}
@Test
fun whenRetrieveElementsFirstAndLast_thenSuccess() {
assertEquals("Australia", classUnderTest.retrieveElementsFirstAndLast())
}
@Test
fun whenRetrieveSubList_thenSuccess() {
assertEquals(3, classUnderTest.retrieveSubList().size)
}
@Test
fun whenRetrieveListSliceUsingIndices_thenSuccess() {
assertEquals(4, classUnderTest.retrieveListSliceUsingIndices().size)
}
@Test
fun whenRetrieveListSliceUsingIndicesList_thenSuccess() {
assertEquals(2, classUnderTest.retrieveListSliceUsingIndicesList().size)
}
@Test
fun whenCountList_thenSuccess() {
assertEquals(5, classUnderTest.countList())
}
@Test
fun whenCountListUsingPredicate_thenSuccess() {
assertEquals(3, classUnderTest.countListUsingPredicate())
}
@Test
fun whenCountListUsingProperty_thenSuccess() {
assertEquals(5, classUnderTest.countListUsingProperty())
}
@Test
fun whenAddToList_thenSuccess() {
assertEquals(11, classUnderTest.addToList().count())
}
@Test
fun whenRemoveFromList_thenSuccess() {
val list = classUnderTest.removeFromList()
assertEquals(3, list.size)
assertEquals("Sao Paulo", list[1])
}
@Test
fun whenReplaceFromList_thenSuccess() {
val list = classUnderTest.replaceFromList()
assertEquals(5, list.size)
assertEquals("Barcelona", list[1])
}
@Test
fun whenSortMutableList_thenSuccess() {
assertEquals("Sydney", classUnderTest.sortMutableList()[0])
}
@Test
fun whenSortList_thenSuccess() {
assertEquals("India", classUnderTest.sortList()[1])
}
@Test
fun whenCheckOneElementInList_thenSuccess() {
assertTrue(classUnderTest.checkOneElementInList())
}
@Test
fun whenCheckOneElementInListUsingOperator_thenSuccess() {
assertFalse(classUnderTest.checkOneElementInListUsingOperator())
}
@Test
fun whenCheckElementsInList_thenSuccess() {
assertTrue(classUnderTest.checkElementsInList())
}
}

View File

@ -11,5 +11,6 @@ This module contains articles about core features in the Kotlin language.
- [Lazy Initialization in Kotlin](https://www.baeldung.com/kotlin-lazy-initialization)
- [Comprehensive Guide to Null Safety in Kotlin](https://www.baeldung.com/kotlin-null-safety)
- [Kotlin Scope Functions](https://www.baeldung.com/kotlin-scope-functions)
- [If-Else Expression in Kotlin](https://www.baeldung.com/kotlin/if-else-expression)
- [Checking Whether a lateinit var Is Initialized in Kotlin](https://www.baeldung.com/kotlin/checking-lateinit)
- [[<-- Prev]](/core-kotlin-modules/core-kotlin-lang)
- [[<-- Prev]](/core-kotlin-modules/core-kotlin-lang)