我有以下数据类类别:
data class Category(
val id: Int = DEFAULT_ID,
val name: String = "",
val picture: String = "",
val subcategories: List<Category> = listOf()
)
Run Code Online (Sandbox Code Playgroud)
我正在构建一个函数,该函数接受 id 列表,并且需要在类别列表中搜索(如果该列表包含这些 id)。如果它包含id,我需要将类别保存在categoryListResult中。
这就是我编写的方式,并且它有效,但我不确定这是否是 Kotlin 中最有效的方法。
private fun getPopCategories(listOfIds : MutableList<Int>) {
val categoryListResult = mutableListOf<Category>()
getCategories.execute(
onSuccess = { categories -> categories.forEach{ category ->
if (listOfIds.contains(category.id)) categoryListResult.add(category)
if (category.hasSubcategories()) {
category.subcategories.forEach { subcategory ->
if (listOfIds.contains(subcategory.id)) categoryListResult.add(subcategory)
}
}
}
}
)
}
Run Code Online (Sandbox Code Playgroud)
使用 kotlin 的谓词find
得到 ONE。
listOf("Hello", "Henry", "Alabama").find { it.startsWith("He") }
// Returns the first match of the list
Run Code Online (Sandbox Code Playgroud)
如果您希望所有这些都符合特定条件,请使用 filter
listOf("Hello", "Henry", "Alabama").filter { it.startsWith("He") }
// Returns "Hello" and "Henry"
Run Code Online (Sandbox Code Playgroud)
因此,在您的情况下,理想的做法是获取类别的平面列表(包括您的子类别;为此,我建议使用flatMap, flatten
或类似的谓词。
// This way you just have an entire List<Category>
// This is a naive approach that assumes that subcategories won't have subcategories
val allCategories = categories.flatMap { cat -> listOf(cat) + cat.subcategories.orEmpty()
}
Run Code Online (Sandbox Code Playgroud)
最后做
allCategories.filter { cat -> cat.id in listOfIds }
Run Code Online (Sandbox Code Playgroud)
您可以在kotlin.collections包中阅读所有这些谓词。