Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search for items in a list Kotlin

Tags:

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

like image 247
Praveen P. Avatar asked Dec 30 '25 07:12

Praveen P.


1 Answers

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.

like image 171
Some random IT boy Avatar answered Jan 02 '26 17:01

Some random IT boy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!