14

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.

2
  • Does Product have a unique property(ies)? Commented Oct 17, 2011 at 4:59
  • 1
    Assume that field1 is a field within Product class, so you can do this Map<String, Product> urMap = yourList.stream().collect(Collectors.toMap(Product::getField1, Function.identity())); Commented Feb 7, 2017 at 15:07

3 Answers 3

23

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); } 
Sign up to request clarification or add additional context in comments.

1 Comment

Iterating is kinda slow. There has to be a faster way.
1

Using a supposed name property as the map key:

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

Comments

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); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.