Skip to content

Filter one list using other list in fastest way?

I have one list of objects of Food with fields name and price. I have other list of objects of Category with fields food_name and its category_name.

Now, I want to filter the first list according to the category_name in the second list. How can I do it in fastest way possible?

I am tagging few languages because I just need the filtering logic on any language.

For e.g. in Dart

List<Food> foods = [Food(name: 'Mango', price: 50), Food(name: 'Cucumber', price: 100)];
List<Category> categories = [Category(name: 'Fruits', foodName: 'Mango'), Category(name: 'Vegetables', foodName: 'Cucumber')  ];

I want to filter the list of foods according to category name from second list in fastest way possible.

Answer

Using two lists this will cost you O(n^2) time, you should instead consider using a map structure. In Kotlin this can be done as

val map = foodList.associateBy { it.name }
val result = mutableListOf<Food>()
categoryList.forEach {
    if(map.containsKey(it.foodName)) { result.add(map[it.foodName]) }
}