Java中按店铺分组统计销量Top100商品的实现方案问询
解决方案:提取各店铺销量Top100商品
核心思路
咱们分三步就能搞定这个需求:
- 先按
shopId把所有交易分组,把同一店铺的交易归到一块儿 - 在每个店铺的分组里,再按
productReference聚合,对quantity求和得到每个商品的总销量 - 最后给每个店铺的商品按销量从高到低排序,取前100个
代码实现
用Java Stream API来做最简洁高效,直接上代码:
import java.util.*; import java.util.stream.Collectors; public class TransactionAnalyzer { public static Map<String, List<Map.Entry<Integer, Integer>>> getShopTop100Products(List<Transaction> transactions) { return transactions.stream() // 第一步:按店铺分组,再按商品聚合总销量 .collect(Collectors.groupingBy( Transaction::getShopId, Collectors.groupingBy( Transaction::getProductReference, Collectors.summingInt(Transaction::getQuantity) ) )) // 第二步:对每个店铺的商品销量排序,取Top100 .entrySet().stream() .collect(Collectors.toMap( Map.Entry::getKey, entry -> entry.getValue().entrySet().stream() // 按销量降序排序 .sorted(Map.Entry.<Integer, Integer>comparingByValue().reversed()) // 截取前100个商品 .limit(100) .collect(Collectors.toList()) )); } } // 你的Transaction类需要有对应的getter方法,示例如下 class Transaction { private int transactionID; private Date transactionDate; private String shopId; private int productReference; private int quantity; private float price; // 构造函数、getter和setter请自行实现 public String getShopId() { return shopId; } public int getProductReference() { return productReference; } public int getQuantity() { return quantity; } }
关键细节说明
- 分组与聚合:两层
groupingBy嵌套,第一层按店铺划分,第二层在店铺内统计每个商品的总销量,最终得到店铺ID -> 商品ID-总销量映射的结构。 - 排序规则:默认按销量降序排列,如果两个商品销量相同,会保持它们在原集合中的顺序。要是需要自定义相同销量的排序逻辑(比如按商品ID升序),可以修改
sorted部分:.sorted((e1, e2) -> { int销量对比 = e2.getValue().compareTo(e1.getValue()); return 销量对比 != 0 ? 销量对比 : e1.getKey().compareTo(e2.getKey()); }) - 边界情况:如果某个店铺的商品数量不足100个,会直接返回该店铺的所有商品,不会补全空数据。
内容的提问来源于stack exchange,提问作者rafik_bougacha
相关产品推荐
相关产品推荐

