我有数组
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转换为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 */
}
我想转换为这样的 map :
{1980= [Arizona,A], [NewYork,C]},
{1970= [NewYork,B],[NewYork,D]},
{1960= [California,E]}
如何通过将数组列表转换为 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)
}
根据问题的更新,请注意,year
是私有(private)的,但我假设它在上下文中是可读的。以下代码未经测试,但应该可以让您非常接近。
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));
}
关于java - 将 ArrayList 转换为 Map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22927875/