首页 > 解决方案 > 通过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(或任何其他解决方案)来保留订单以及如何做到这一点?

标签: javajava-streamgroupingby

解决方案


正如在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>最后一个参数。


推荐阅读