将ArrayList转换为HashMap [英] Converting ArrayList to HashMap

查看:153
本文介绍了将ArrayList转换为HashMap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

Java:如何将列表转换为地图

我有arrayList

I have arrayList

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

我想将ArrayList转换为HashMap像这样

I want to convert to ArrayList to HashMap Like this

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

请帮我看看如何转换为HashMap。

Please help me how to convert to HashMap.

推荐答案

一般方法是迭代 ArrayList ,并将值插入 HashMap 。示例如下:

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

这篇关于将ArrayList转换为HashMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆