Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting ArrayList to HashMap [duplicate]

Tags:

java

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.

like image 670
Piraba Avatar asked Oct 17 '11 04:10

Piraba


1 Answers

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);
}
like image 174
Jon Newmuis Avatar answered Sep 23 '22 03:09

Jon Newmuis