将ArrayList转换为Map

时间:2014-04-08 04:57:54

标签: java list arraylist map

我有arrayList

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

此列表存储在ArrayList中。问题是当我打印数据时,我得到:

A, Arizona, 1980
B, Arizona, 1970
C, NewYork, 1980
D, NewYork, 1970
E, California, 1960

我想根据区域转换为ArrayList to Map:

Map<Integer, Map<String, List<Product>>>//Integer here is year and String here is manufacturingArea

Product bean具有以下结构:

class Product{
    private String name;
    private String manufacturingArea;
    private int year;
    /* Getters and setters*/
    /* toString method */
}

我想像这样转换为地图:

{1980= [Arizona,A], [NewYork,C]},
{1970= [NewYork,B],[NewYork,D]},
{1960= [California,E]}

如何通过将arraylist转换为map来分组数据?

1 个答案:

答案 0 :(得分:7)

也许是这样的?

Map<String, List<Product>> newMap = new HashMap<String, List<Product>>();

for (Product product: productList) {
   if (!newMap.containsKey(product.name)) 
        newMap.put(product.name, new ArrayList<Product>())
   newMap.get(product.name).add(product)
}

根据问题的更新,请注意year是私有的,但我认为它在上下文中是可读的。以下代码未经测试,但应该非常接近。

Map<Integer, Map<String, List<Product>>> newMap = new HashMap<Integer, Map<String, List<<Product>>>();
for (Product product: productList) {
   if (!newMap.containsKey(product.year)) // Java should do auto-boxing here 
        newMap.put(product.year, new HashMap<String, Product>());
   if (!newMap.get(product.year).containsKey(product.manufacturingArea);
        newMap.get(product.year).put(product.manufacturingArea, new ArrayList<Product>());

   newMap.get(product.year).get(product.manufacturingArea).add(product));
}