Java 将ArrayList转换为HashMap

Java 将ArrayList转换为HashMap,java,Java,可能重复: 我有arrayList ArrayList<Product> productList = new ArrayList<Product>(); productList = getProducts(); //Fetch the result from db ArrayList productList=new ArrayList(); productList=getProducts()//从数据库中获取结果 我想像这样将ArrayList转换为Hash

可能重复:

我有arrayList

ArrayList<Product> productList  = new ArrayList<Product>();
 productList  = getProducts();  //Fetch the result from db
ArrayList productList=new ArrayList();
productList=getProducts()//从数据库中获取结果
我想像这样将ArrayList转换为HashMap

  HashMap<String, Product> s= new HashMap<String,Product>();
HashMap s=newhashmap();

请帮助我如何转换为HashMap。

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

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

一般的方法是遍历
ArrayList
,并将值插入
HashMap
。例如:

HashMap<String, Product> productMap = new HashMap<String, Product>();
for (Product product : productList) {
   productMap.put(product.getProductCode(), product);
}
HashMap productMap=newhashmap();
对于(产品:productList){
productMap.put(product.getProductCode(),product);
}
[已编辑]

使用您关于productCode的注释(假设productCode是字符串)作为参考

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

Product
是否具有唯一属性?假设field1是Product类中的一个字段,因此可以执行此操作
Map urMap=yourList.stream().collect(Collectors.toMap(Product::getField1,Function.identity())迭代有点慢。必须有一个更快的方法。