Skip to content

Collection: Find a particular element based on a certain condition

Devrath edited this page Feb 29, 2024 · 2 revisions

Single

If there is just one item that satisfies the condition

Code

data class Country(val name: String, val isDemocracy: Boolean)
val countriesList = mutableListOf(
    Country(name = "USA", isDemocracy = true),
    Country(name = "Australia", isDemocracy = true),
    Country(name = "Russia", isDemocracy = false),
    Country(name = "England", isDemocracy = true),
    Country(name = "North Korea", isDemocracy = false)
)


fun main(args: Array<String>) {

    val output = countriesList.single {
        it.name == "USA"
    }

    println("Result-> $output")

}

Output

Result-> Country(name=USA, isDemocracy=true)

If there is more than one item that satisfies the condition

Code

val countriesList = mutableListOf(
    Country(name = "USA", isDemocracy = true),
    Country(name = "Australia", isDemocracy = true),
    Country(name = "Russia", isDemocracy = false),
    Country(name = "England", isDemocracy = true),
    Country(name = "North Korea", isDemocracy = false)
)


fun main(args: Array<String>) {

    val output = countriesList.single {
        it.isDemocracy
    }

    println("Result-> $output")

}

Output

Exception in thread "main" java.lang.IllegalArgumentException: Collection contains more than one matching element.
	at MainKt.main(Main.kt:32)

all

Code

val countriesList = mutableListOf(
    Country(name = "USA", isDemocracy = true),
    Country(name = "Australia", isDemocracy = true),
    Country(name = "Russia", isDemocracy = false),
    Country(name = "England", isDemocracy = true),
    Country(name = "North Korea", isDemocracy = false)
)


fun main(args: Array<String>) {

    val output = countriesList.find {
        it.name=="India"
    }

    println("Result-> $output")

}

Output

Result-> null
Clone this wiki locally