2014-11-02 114 views
0

我需要根據此ArrayList中的變量將包含基本數據類型String和ArrayLists的ArrayList分割爲幾個ArrayLists。根據變量將ArrayList分成若干個ArrayLists

我有我的ArrayList purchaseOrderList與許多其他類型的「品牌」字符串。我想將這個ArrayList分成許多新的ArrayLists,因爲我擁有不同的品牌。無論我如何做,我總是以無限循環結束。

ArrayList<Brand> brandList = new ArrayList<Brand>(); 

brandList.add(new Brand(purchaseOrderList.get(0).getBrand())); 
for (int i = 0; i < brandList.size(); i++) { 
    for (Item item : purchaseOrderList) { 
     if (brandList.get(i).getBrand().equals(item.getBrand())) { 
      brandList.get(i).setItemList(item); //Add the items from the purchaseOrderList 
     } else { 
      brandList.add(new Brand(item.getBrand())); 
     } 
    } 
} 

有什麼建議嗎?

+0

使用['地圖<品牌,列表>'](http://docs.oracle.com/javase/7/ docs/api/java/util/Map.html)或['Multimap'](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Multimap.html) – 2014-11-02 17:38:50

+0

另外,在上面的例子中,'List'中只有一個'Brand'。 – 2014-11-02 17:40:03

+0

不使用地圖是不可能的? – Klelund 2014-11-02 17:43:09

回答

0

對於這種問題你應該使用地圖:

Map<Brand, ArrayList<Item>> map = new HashMap<Brand, ArrayList<Item>>(); 


for(Item item : purchaseOrderList){ 
    if(map.get(item.getBrand()) == null) 
    map.put(item.getBrand(), new ArrayList<Item>()); 
    else 
    map.get(item.getBrand()).add(item); 
} 
+0

Thx。輕鬆實施。現在我希望這可以在我的GWT項目中正常工作。 – Klelund 2014-11-02 18:21:03

0

你有一個無限循環,因爲你想遍歷一個數組的所有元素,但在同一時間你添加新的元素。

你應該使用:int arraySize = brandList.size();和使用它的值在第一個的,就像這樣:for (int i = 0; i < arraySize; i++)

這樣你會遍歷所有那些在brandList數組開始的元素, 我想這就是你想要的去做。