Kiran
Kiran

Reputation: 20313

Converting ArrayList to Map

I have arrayList

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

This list is stored in an ArrayList. The problem is that when I print its data, I obtain :

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

I want to convert to ArrayList to Map based on area:

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

The Product bean has the following structure :

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

I'd like to convert to map like this :

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

how can I group the data by converting arraylist to map?

Upvotes: 0

Views: 8705

Answers (1)

merlin2011
merlin2011

Reputation: 75555

Maybe something like this?

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

Per the update to the question, note that year is private, but I am assuming it is readable in the context. The following code is untested, but should get you pretty close.

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

Upvotes: 7

Related Questions