Android Specific Find Object By Matching Properties In A Collection On Predicate
I have a collection of 10,000 objects that have two properties: a string and a string[] class Product { String name; String[] aliases; } Each object is roughly 64 bytes, so we
Solution 1:
Canonical Kotlin, which would work on any version of Android regardless of Java Streams since it doesn't use them would be:
dataclassProduct(val name: String, val aliases: Array<String>)
// written as an extension function, but doesn't have to be...fun List<Product>.isProductOrAlias(text: String): String {
returnthis.firstOrNull { product ->
product.name.equals(text, ignoreCase = true) ||
product.aliases.any { alias ->
alias.equals(text, ignoreCase = true)
}
}?.name ?: ""
}
funtest() {
// assume somewhere this was createdval products = listOf<Product>(...)
println(products.isProductOrAlias("something")) // prints name of Product or ""
}
See Kotlin API reference for the standard library:
collection extension function
firstOrNull()
array extension function
any()
string extension function
equals()
Kotlin Elvis operator
?:
Kotlin Safecalls
?.
Post a Comment for "Android Specific Find Object By Matching Properties In A Collection On Predicate"