-
Notifications
You must be signed in to change notification settings - Fork 22
Collection: Find a particular element based on a certain condition
Devrath edited this page Feb 29, 2024
·
2 revisions
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)
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)
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