13

Possible Duplicate:
Java: How to convert List to Map

I have arrayList

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

I want to convert to ArrayList to HashMap Like this

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

Please help me how to convert to HashMap.

Community
  • 1
  • 1
Piraba
  • 6,974
  • 17
  • 85
  • 135
  • Does `Product` have a unique property(ies)? – SimonC Oct 17 '11 at 04:59
  • 1
    Assume that **field1** is a field within _**Product**_ class, so you can do this `Map urMap = yourList.stream().collect(Collectors.toMap(Product::getField1, Function.identity()));` – Jad Chahine Feb 07 '17 at 15:07

3 Answers3

22

The general methodology would be to iterate through the ArrayList, and insert the values into the HashMap. An example is as follows:

HashMap<String, Product> productMap = new HashMap<String, Product>();
for (Product product : productList) {
   productMap.put(product.getProductCode(), product);
}
Jon Newmuis
  • 25,722
  • 2
  • 45
  • 57
1

Using a supposed name property as the map key:

for (Product p: productList) { s.put(p.getName(), p); }
kevin cline
  • 2,608
  • 2
  • 25
  • 38
1

[edited]

using your comment about productCode (and assuming product code is a String) as reference...

 for(Product p : productList){
        s.put(p.getProductCode() , p);
    }
Yevgeny Simkin
  • 27,946
  • 39
  • 137
  • 236