Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 将ArrayList转换为Map_Java_List_Arraylist_Map - Fatal编程技术网

Java 将ArrayList转换为Map

Java 将ArrayList转换为Map,java,list,arraylist,map,Java,List,Arraylist,Map,我有arrayList ArrayList<Product> productList = new ArrayList<Product>(); productList = getProducts(); //Fetch the result from db 我想将ArrayList转换为基于面积的地图: Map<Integer, Map<String, List<Product>>>//Integer here is year a

我有arrayList

ArrayList<Product> productList  = new ArrayList<Product>();
 productList  = getProducts();  //Fetch the result from db
我想将ArrayList转换为基于面积的地图:

Map<Integer, Map<String, List<Product>>>//Integer here is year and String here is manufacturingArea
我想转换成这样的地图:

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

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

可能是这样的情况

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

你必须将它映射到数组上的一个循环来创建映射。和另一个循环来打印地图。你试过什么?你的地图声明和你的数据不匹配。我感觉OP想知道如何以他/她想要的格式打印,而不是如何将其转换为地图。但是,当然,我可能也错了@Ɍ。Ɉ,他在我编辑后删除了接受,所以我猜他不想要它:P@merlin2011:我试过上面的代码。HashMap在概念上替换与映射中给定键相关联的上一个值,就像对基元类型的数组索引操作一样。@未知,请检查此项。@merlin2011-老实说,我希望您保留答案的两个部分。你看,额外的信息永远不会有害:
{1980= [Arizona,A], [NewYork,C]},
{1970= [NewYork,B],[NewYork,D]},
{1960= [California,E]}
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)
}
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));
}