首页 > 解决方案 > 使用 java 流将 BrandName 和 Product 的 SimpleEntry 列表转换为 brandName 到产品列表的映射

问题描述

我正在寻找将列表转换SimpleEntry<String, Product>Map<String, List<Product>. 字符串是brandName,每个brandName 都有产品。所以,我想转换List<SimpleEntry<>Map<String, List<Product>地图中的位置,我得到一个品牌的产品列表。

目前,我正在使用以下代码,但我认为这也可以通过流来完成

//List<AbstractMap.SimpleEntry<String, Product>> listOfSimpleEntries = new ArrayList<>() is a list of simple Entries 
//e.g. 
//nike, productA 
//adidas, productB,
//nike, productC

Map<String, List<Product>> brandToProductsMap = new HashMap<>();
for (AbstractMap.SimpleEntry<String, Product> simpleEntry : listOfSimpleEntries) {
    if (!brandToProductsMap.containsKey(simpleEntry.getKey())) {
        brandToProductsMap.put(simpleEntry.getKey(), new ArrayList<>());
    }
    brandToProductsMap.get(simpleEntry.getKey()).add(simpleEntry.getValue());
}

我试图用下面的流替换上面的代码,但我得到java.util.ArrayList 无法转换为 Product

Map<String, List<Product>> brandToProductsMap = listOfSimpleEntries.stream().collect(Collectors.groupingBy(
          w -> w.getKey(), Collectors.mapping(x -> x.getValue(), Collectors.toList())));

有人可以指出我在这里缺少什么吗?谢谢。

编辑 2 我编写的代码作为一个单独的程序工作,但不是项目的一部分。我发现在目标文件夹中,代码编译如下,看起来不正确。

        Map<String, List<Product>> brandToProductsMap = (Map)listOfSimpleEntries.stream().collect(Collectors.groupingBy((w) -> {
            return (String)w.getKey();
        }, Collectors.mapping((x) -> {
            return (Product)x.getValue();
        }, Collectors.toList())));
        Iterator var5 = brandToProductsMap .entrySet().iterator();

标签: javajava-stream

解决方案


你可以做:

List<AbstractMap.SimpleEntry<String, Product>> entries = Arrays.asList(
        new AbstractMap.SimpleEntry<>("Nike", new Product("ProductA")),
        new AbstractMap.SimpleEntry<>("Adidas", new Product("ProductB")),
        new AbstractMap.SimpleEntry<>("Nike", new Product("ProductC"))
);

Map<String, List<Product>> brandNameToProduct = entries.stream()
        .collect(Collectors.groupingBy(e -> e.getKey(), 
                Collectors.mapping(e -> e.getValue(), Collectors.toList())));

System.out.println(brandNameToProduct);

输出:

{Nike=[Product(name=ProductA), Product(name=ProductC)], Adidas=[Product(name=ProductB)]}

编辑:

我想你和我做的一模一样,所以也许你的 IDE 疯了。


推荐阅读