Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
83 views
in Technique[技术] by (71.8m points)

Search for items in a list Kotlin

I have the following data class Category:

data class Category(
  val id: Int = DEFAULT_ID,
  val name: String = "",
  val picture: String = "",
  val subcategories: List<Category> = listOf()
)

And I am building a function that takes a list of ids and needs to search in a list of Categories if the list contains those ids. If it contains the id, I need to save the Category in categoryListResult.

This is how I've written it, and it works, but I am not sure if it's the most efficient way to do so in 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)
            }
          }
        }
      }
    )
  }

question from:https://stackoverflow.com/questions/65883879/search-for-items-in-a-list-kotlin

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use kotlin's predicate find to get ONE.

listOf("Hello", "Henry", "Alabama).find { it.startsWith("He") }
// Returns the first match of the list

If you want all of them matching a certain condition use filter

listOf("Hello", "Henry", "Alabama).filter { it.startsWith("He") }
// Returns "Hello" and "Henry"

So in your case the ideal thing to do would be to get a flat list of categories (including your subcategories; for this I reccomend the use of flatMap, flatten or similar predicates.

// 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()
}

And finally do

allCategories.filter { cat -> cat.id in listOfIds }

You can read about all these predicates in the kotlin.collections package.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...