java - 通过java流收集到hashMap的多个组
问题描述
我有以下对象:
List<CartItem> cartItemsList = cart.getItems().stream()
.sorted(Comparator.comparingDouble(f -> f.getProduct().getPrice()))
.collect(Collectors.toList());
Map<Product, Map<Customization, List<CartItem>>> map =cartItemsList.stream()
.collect(Collectors.groupingBy(CartItem::getProduct,
Collectors.groupingBy(CartItem::getCustomizations)));
我的问题是关于地图:因为我需要保留在第一个 list(cartItemsList) 中定义的顺序,所以地图不是一个好的解决方案。我是否必须使用linkedHashMap(或任何其他解决方案)来保留订单以及如何做到这一点?
解决方案
正如在javadoc中提到的,Supplier<Map>
分类器之后。
Map<Product, Map<Customization, List<CartItem>>> map = cartItemsList.stream()
.collect(Collectors.groupingBy(
CartItem::getProduct,
LinkedHashMap::new,
Collectors.groupingBy(CartItem::getCustomizations)
));
如果嵌套映射也需要LinkedHashMap
,则应使用以下代码:
Map<Product, Map<Customization, List<CartItem>>> map = cartItemsList.stream()
.collect(Collectors.groupingBy(
CartItem::getProduct,
LinkedHashMap::new,
Collectors.groupingBy(
CartItem::getCustomizations,
LinkedHashMap::new,
Collectors.toList()
)
));
因为Collectors.toMap
也可以使用4 参数重载提供特定的Map ,其中Supplier<Map>
最后一个参数。
推荐阅读
- android - 通知仅显示在顶部栏中
- reactjs - 使用 hookrouter 反应 Material UI Button 组件
- shiny - 将shinyWidgets添加到R中的数据表中
- c++ - 是否可以通过指向不同的、不相关的子对象的指针来获取指向一个子对象的指针?
- node.js - Postgres 简单查询失败,没有错误
- html - 使 flexbox 项目宽度等于兄弟元素的组合宽度
- sql - 联合查询减去总数
- javascript - 将 jquery 中的默认值放入 textarea 时缺少 \
- git - 新文件夹中的哪些文件将由 git 添加
- visual-studio-code - VS Code editor.overviewRulerLanes 设置有什么作用?