Home > database >  How to merge two case class sequences based on an id in Scala?
How to merge two case class sequences based on an id in Scala?

Time:06-11

I have a case class which is list of restaurants:

case class RestaurantSearchResponse(
                                  restaurant: Restaurant,
                                  city: CityDetail
                                )

  case class Restaurant(
                    id: Long,
                    name: String,
                    rating: BigDecimal
                  )

RestaurantSearchResponse is what we return at the moment from API. Now I have another case class that has list of restaurants with the sales_count like below:

case class HighSellerSort(
                           id: Long = 0L,
                           restaurantId: Long,
                           orders_count: Int
                         )

So now on API side I have sequence of restaurants and also a sequence of HighSellerSort. They can get merged based on restaurantId which is present on both case classes. How can I merge them and then sort based on orders_count.

NOTE: There might not be a record in HighSellerSort for a specific restaurant.

CodePudding user response:

The important first step is to convert your sales sequence into a Map, so that your logic does not become quadratic, like it is in the accepted answer.

val lookup = sales
   .map { s => s.restaurant_id -> s.orders_count }
   .toMap
   .withDefault(_ => 0)

Now, if you just need to sort:

restaurants.sortBy { r => lookup(r.id) }

Or if you want to tag each restaurant with a count:

restaurants.map { r => r -> r.lookup(r.id) }

Or if you want both

restaurants.map { r => r -> r.lookup(r.id) }.sortBy(_._2)

CodePudding user response:

Basically you need to iterate over your restaurants, and look for a HighSellerSort that corresponds to the restaurant. So based on my assumptions about your questions, this can be the approach:

def merge(
  restaurants: Seq[Restaurant],
  sorts: Seq[HighSellerSort]
  ): Seq[(Restaurant, Option[HighSellerSort])] = {
  restaurants.map { restaurant =>
    restaurant -> sorts.collectFirst {
      case sort if sort.restaurantId == restaurant.id => sort
    }
  }
}
  • Related