java - 使用 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();
解决方案
你可以做:
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 疯了。
推荐阅读
- c# - .NET MVC 路由在菜单控制器上重定向到特定控制器
- linux - 想知道我是否可以在它执行时应用加载,这可能吗?
- java - 我怎样才能通过列表
进入可变参数方法 - python - 错误:OpenCV(4.1.2)/io/opencv/modules/imgcodecs/src/loadsave.cpp:715:错误:(-215:断言失败)!_img.empty()在函数'imwrite'中
- python - 如何为具有可以访问主 GUI 功能的子窗口/类的窗口创建 GUI 类?
- android - Sqlite如何提高性能?
- python - Pydantic验证器删除空白字符串?
- c - 我想按字母顺序对结构进行排序,但如果我进行排序,我的程序不会给出任何输出
- excel - 如何从 sheet1 的范围中提取一些信息并将其放在组合框中
- python - 1)为什么会出现“无效语法”(代码中突出显示的行)?2)错误解决后,为什么python只读取if语句?