多组按java流收集到hashMap

多组按java流收集到hashMap,java,java-stream,groupingby,Java,Java Stream,Groupingby,我有以下物品: List<CartItem> cartItemsList = cart.getItems().stream() .sorted(Comparator.comparingDouble(f -> f.getProduct().getPrice())) .collect(Collectors.toList()); Map<Product, Map<Customization, List&

我有以下物品:

 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=cart.getItems().stream()
.sorted(Comparator.comparingDouble(f->f.getProduct().getPrice()))
.collect(Collectors.toList());
Map Map=cartItemsList.stream()
.collect(收集器).groupingBy(CartItem::getProduct、,
Collectors.groupingBy(CartItem::getCustomizations));
我的问题是关于map的:因为我需要保留第一个列表(cartItemsList)中定义的顺序,所以map不是一个好的解决方案。我是否必须使用linkedHashMap(或任何其他解决方案)来维护订单?如何做到这一点?

如中所述,
供应商
在分类器之后

Map Map=cartItemsList.stream()
.collect(收集器.groupingBy(
CartItem::getProduct,
LinkedHashMap::新建,
Collectors.groupingBy(CartItem::getCustomizations)
));
如果嵌套映射也需要
LinkedHashMap
,则应使用以下代码:

Map Map=cartItemsList.stream()
.collect(收集器.groupingBy(
CartItem::getProduct,
LinkedHashMap::新建,
收集者分组(
CartItem::getCustomizations,
LinkedHashMap::新建,
收集者
)
));


对于
collector.toMap
也可以使用
Supplier
的最后一个参数提供特定的映射。

这对您有帮助吗?如果您需要按插入顺序保留元素的
Map
,那么是的,
LinkedHashMap
是一个不错的选择。是的,
收集器。groupingBy
有一个重载版本parameter@Madlemon也许..如何将此示例应用到我的场景中?例如,
.collect(LinkedHashMap::new,(map,cartItem)->map.put(cartItem.getProduct(),cartItem.getCustomizations()),Map::putAll);