将ArrayList转换为HashMap

13

可能是重复问题:
Java:如何将List转换为Map

我有一个ArrayList

ArrayList<Product> productList  = new ArrayList<Product>();
 productList  = getProducts();  //Fetch the result from db

我想将ArrayList转换为HashMap,就像这样

  HashMap<String, Product> s= new HashMap<String,Product>();
请帮我如何转换成HashMap。

Product 是否具有唯一的属性? - SimonC
1
假设field1是_Product_类中的一个字段,您可以这样实现:Map<String, Product> urMap = yourList.stream().collect(Collectors.toMap(Product::getField1, Function.identity())); - Jad Chahine
3个回答

22

通常的方法是遍历 ArrayList,并将其中的值插入到 HashMap 中。以下是一个示例:

HashMap<String, Product> productMap = new HashMap<String, Product>();
for (Product product : productList) {
   productMap.put(product.getProductCode(), product);
}

迭代有点慢。一定有更快的方法。 - IgorGanapolsky

1

使用一个假定的名称属性作为映射键:

for (Product p: productList) { s.put(p.getName(), p); }

1

[编辑]

以您有关productCode的评论为参考(并假设产品代码是字符串)...

 for(Product p : productList){
        s.put(p.getProductCode() , p);
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接