Scala中如何根据id合并两个case class序列并按订单数排序
实现方案
你可以基于Scala标准库完成关联、排序逻辑,步骤如下:
- 先将
HighSellerSort序列转换为以restaurantId为键的Map,关联查找的时间复杂度为O(1),整体性能远高于双层遍历匹配 - 遍历
RestaurantSearchResponse序列,通过餐厅id匹配对应的销量数据,无匹配记录的餐厅可按业务需求设置默认销量值(示例默认设为0) - 关联完成后按
orders_count字段排序,可根据需求选择升序/降序规则
核心代码示例
// 业务侧持有的两个原始序列 val restaurantResponses: Seq[RestaurantSearchResponse] = ??? val highSellerSorts: Seq[HighSellerSort] = ??? // 构建餐厅id -> 销量数据的映射 val sellerSortMap: Map[Long, HighSellerSort] = highSellerSorts.map(item => item.restaurantId -> item).toMap // 关联合并数据 val merged: Seq[(RestaurantSearchResponse, Int)] = restaurantResponses.map { resp => val orderCount = sellerSortMap.get(resp.restaurant.id) .map(_.orders_count) .getOrElse(0) // 无匹配记录时默认销量为0,可按需调整 (resp, orderCount) } // 按销量降序排序(销量高的在前),需要升序则去掉reverse参数 val sortedResult: Seq[RestaurantSearchResponse] = merged .sortBy(_._2)(Ordering[Int].reverse) .map(_._1)
可选优化
如果需要在最终结果中保留销量字段,可自定义合并后的结构,无需返回Tuple:
// 合并后的数据结构 case class RestaurantWithSales( restaurantInfo: RestaurantSearchResponse, ordersCount: Int ) // 关联时直接返回自定义结构 val mergedWithType: Seq[RestaurantWithSales] = restaurantResponses.map { resp => val orderCount = sellerSortMap.get(resp.restaurant.id).map(_.orders_count).getOrElse(0) RestaurantWithSales(resp, orderCount) } // 排序逻辑不变 val sortedWithSales: Seq[RestaurantWithSales] = mergedWithType .sortBy(_.ordersCount)(Ordering[Int].reverse)
注意:如果需要将无销量记录的餐厅固定排在列表末尾,也可以在排序时单独配置优先级,不需要依赖默认的0值逻辑。
内容的提问来源于stack exchange,提问作者Alireza
相关产品推荐
相关产品推荐

