Lui
Lui

Reputation: 5

Comparing two different Lists based on Ids

what I am trying to do here is I am trying to find articles by given id from the CustomerFavoriteRepository. I have two different lists (articleList,FavList ) and I am comparing the ids of both lists and adding them to the empty array (FavartList). Does anyone help me with how can I achieve that using for loop? I am getting errors at the point of "FavartList.add()" in the loop i don't know which value I have to give there. thanks

Upvotes: 0

Views: 56

Answers (1)

Michael Horn
Michael Horn

Reputation: 4099

The simple answer to your question is that you need to construct the NewCustomerFav, and pass it to the add method:

//this is what i tried 
for (final article in articleList) {
  for (final customArticle in customerFavList) {
    if (article.id == customArticle.articleId) {
      // The values are just for example - I'm not certain how
      // you mean to derive `id` or `like` for a NewCustomerFav.
      final fav = NewCustomerFav(0, article, 1);
      customFavartList.add(fav);
    }
  }
}

On a different note, your algorithm can be improved here - Right now it will take on the order of n * m operations to build customFavartList, where n is the number of articles, and m is the number of favorites.

It can be reduced so that the algorithm performs on the order of n + m, instead, which will scale much better when there are many articles, and the customer has many favorites.

The way to do it is to create a Set of ids from the favoritesList, something like this:

// Assuming customerFavList is a list of int ids
final customerFavIdSet = Set.from(customerFavList.map((e) => e.articleId));

for (final article in articleList) {
  // Now you can check whether the article is a favorite with this one
  // query, rather than searching the whole list.
  if (customerFavIdSet.contains(article.id) {
    final fav = NewCustomerFav(0, article, 1);
    customFavartList.add(fav);
  }
}

Upvotes: 1

Related Questions