list - 分组,求和然后对事务对象列表进行排序java
问题描述
我有一个按日交易的列表,交易包含以下属性:
Transaction(int transactionID,
DateTime transactionDate,
String shopId,
int productReference,
int quantity,
float price);
有一个列表List<Transaction>
,我想按商店提取前 100 名销售的产品。
因此,我需要先按 shopId 对交易进行分组,然后再按 productReference 对交易进行分组,然后对数量求和,而不是从最畅销到最少进行排序。
感谢您的帮助
解决方案
我建议使用附加Product
类型,被覆盖equals()
并且hasCode()
仅包含shopId和productReference。新类型将作为输出,这将使所有转换工作更加明显。考虑我的版本,使用Lombok lib:
import lombok.*;
@Data
@RequiredArgsConstructor(staticName = "of")
@ToString
public class Product {
final String shopId;
final int productReference;
}
和功能代码本身:
List<Product> products = transactions.stream()
// grouping transactions by the same product
.collect(Collectors.groupingBy(transaction -> Product.of(
transaction.getShopId(),
transaction.getProductReference())))
.entrySet().stream()
// summing all price * quantity occurrences to find top sellings
.collect(Collectors.toMap(
Map.Entry::getKey,
e -> e.getValue().stream()
.mapToDouble(p -> p.getQuantity() * p.getPrice())
.sum()))
.entrySet().stream()
// sorting by the most expensive ones at the top,
// limiting to 10 and collecting to the list
.sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
.map(Map.Entry::getKey)
.limit(10)
.collect(Collectors.toList());
推荐阅读
- angular - 我怎么知道我已经在 Angular 应用程序中单点登录?
- python - 在 Python 中键入一个可变参数函数
- python - 我正在使用乌龟制作蛇游戏,但在制作程序功能时遇到问题,因为它没有移动
- python - 带有面部跟踪器的 python 运动面具
- r - 结合来自两个不同数据集的 glm 模型 (r/rpy2)
- flutter - 如何从给定的颜色中获得 Flutter 中的颜色阴影?
- node.js - 用笑话测试内部错误的存根函数
- python - 如何将多级字典映射到 DataFrame 系列
- vue.js - 如何将相同的道具两次传递给vue组件
- python - 从图像中去除照明噪声以检测四月标签